]> git.lizzy.rs Git - rust.git/blob - src/libcollections/str.rs
Fix invalid associated type rendering in rustdoc
[rust.git] / src / libcollections / str.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Unicode string slices.
12 //!
13 //! The `&str` type is one of the two main string types, the other being `String`.
14 //! Unlike its `String` counterpart, its contents are borrowed.
15 //!
16 //! # Basic Usage
17 //!
18 //! A basic string declaration of `&str` type:
19 //!
20 //! ```
21 //! let hello_world = "Hello, World!";
22 //! ```
23 //!
24 //! Here we have declared a string literal, also known as a string slice.
25 //! String literals have a static lifetime, which means the string `hello_world`
26 //! is guaranteed to be valid for the duration of the entire program.
27 //! We can explicitly specify `hello_world`'s lifetime as well:
28 //!
29 //! ```
30 //! let hello_world: &'static str = "Hello, world!";
31 //! ```
32 //!
33 //! *[See also the `str` primitive type](../../std/primitive.str.html).*
34
35 #![stable(feature = "rust1", since = "1.0.0")]
36
37 // Many of the usings in this module are only used in the test configuration.
38 // It's cleaner to just turn off the unused_imports warning than to fix them.
39 #![allow(unused_imports)]
40
41 use core::fmt;
42 use core::str as core_str;
43 use core::str::pattern::Pattern;
44 use core::str::pattern::{Searcher, ReverseSearcher, DoubleEndedSearcher};
45 use core::mem;
46 use core::iter::FusedIterator;
47 use std_unicode::str::{UnicodeStr, Utf16Encoder};
48
49 use vec_deque::VecDeque;
50 use borrow::{Borrow, ToOwned};
51 use string::String;
52 use std_unicode;
53 use vec::Vec;
54 use slice::{SliceConcatExt, SliceIndex};
55 use boxed::Box;
56
57 #[stable(feature = "rust1", since = "1.0.0")]
58 pub use core::str::{FromStr, Utf8Error};
59 #[allow(deprecated)]
60 #[stable(feature = "rust1", since = "1.0.0")]
61 pub use core::str::{Lines, LinesAny};
62 #[stable(feature = "rust1", since = "1.0.0")]
63 pub use core::str::{Split, RSplit};
64 #[stable(feature = "rust1", since = "1.0.0")]
65 pub use core::str::{SplitN, RSplitN};
66 #[stable(feature = "rust1", since = "1.0.0")]
67 pub use core::str::{SplitTerminator, RSplitTerminator};
68 #[stable(feature = "rust1", since = "1.0.0")]
69 pub use core::str::{Matches, RMatches};
70 #[stable(feature = "rust1", since = "1.0.0")]
71 pub use core::str::{MatchIndices, RMatchIndices};
72 #[stable(feature = "rust1", since = "1.0.0")]
73 pub use core::str::{from_utf8, Chars, CharIndices, Bytes};
74 #[stable(feature = "rust1", since = "1.0.0")]
75 pub use core::str::{from_utf8_unchecked, from_utf8_unchecked_mut, ParseBoolError};
76 #[stable(feature = "rust1", since = "1.0.0")]
77 pub use std_unicode::str::SplitWhitespace;
78 #[stable(feature = "rust1", since = "1.0.0")]
79 pub use core::str::pattern;
80
81 #[unstable(feature = "slice_concat_ext",
82            reason = "trait should not have to exist",
83            issue = "27747")]
84 impl<S: Borrow<str>> SliceConcatExt<str> for [S] {
85     type Output = String;
86
87     fn concat(&self) -> String {
88         if self.is_empty() {
89             return String::new();
90         }
91
92         // `len` calculation may overflow but push_str will check boundaries
93         let len = self.iter().map(|s| s.borrow().len()).sum();
94         let mut result = String::with_capacity(len);
95
96         for s in self {
97             result.push_str(s.borrow())
98         }
99
100         result
101     }
102
103     fn join(&self, sep: &str) -> String {
104         if self.is_empty() {
105             return String::new();
106         }
107
108         // concat is faster
109         if sep.is_empty() {
110             return self.concat();
111         }
112
113         // this is wrong without the guarantee that `self` is non-empty
114         // `len` calculation may overflow but push_str but will check boundaries
115         let len = sep.len() * (self.len() - 1) +
116                   self.iter().map(|s| s.borrow().len()).sum::<usize>();
117         let mut result = String::with_capacity(len);
118         let mut first = true;
119
120         for s in self {
121             if first {
122                 first = false;
123             } else {
124                 result.push_str(sep);
125             }
126             result.push_str(s.borrow());
127         }
128         result
129     }
130
131     fn connect(&self, sep: &str) -> String {
132         self.join(sep)
133     }
134 }
135
136 /// An iterator of [`u16`] over the string encoded as UTF-16.
137 ///
138 /// [`u16`]: ../../std/primitive.u16.html
139 ///
140 /// This struct is created by the [`encode_utf16`] method on [`str`].
141 /// See its documentation for more.
142 ///
143 /// [`encode_utf16`]: ../../std/primitive.str.html#method.encode_utf16
144 /// [`str`]: ../../std/primitive.str.html
145 #[derive(Clone)]
146 #[stable(feature = "encode_utf16", since = "1.8.0")]
147 pub struct EncodeUtf16<'a> {
148     encoder: Utf16Encoder<Chars<'a>>,
149 }
150
151 #[stable(feature = "collection_debug", since = "1.17.0")]
152 impl<'a> fmt::Debug for EncodeUtf16<'a> {
153     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
154         f.pad("EncodeUtf16 { .. }")
155     }
156 }
157
158 #[stable(feature = "encode_utf16", since = "1.8.0")]
159 impl<'a> Iterator for EncodeUtf16<'a> {
160     type Item = u16;
161
162     #[inline]
163     fn next(&mut self) -> Option<u16> {
164         self.encoder.next()
165     }
166
167     #[inline]
168     fn size_hint(&self) -> (usize, Option<usize>) {
169         self.encoder.size_hint()
170     }
171 }
172
173 #[unstable(feature = "fused", issue = "35602")]
174 impl<'a> FusedIterator for EncodeUtf16<'a> {}
175
176 // Return the initial codepoint accumulator for the first byte.
177 // The first byte is special, only want bottom 5 bits for width 2, 4 bits
178 // for width 3, and 3 bits for width 4
179 macro_rules! utf8_first_byte {
180     ($byte:expr, $width:expr) => (($byte & (0x7F >> $width)) as u32)
181 }
182
183 // return the value of $ch updated with continuation byte $byte
184 macro_rules! utf8_acc_cont_byte {
185     ($ch:expr, $byte:expr) => (($ch << 6) | ($byte & 63) as u32)
186 }
187
188 #[stable(feature = "rust1", since = "1.0.0")]
189 impl Borrow<str> for String {
190     #[inline]
191     fn borrow(&self) -> &str {
192         &self[..]
193     }
194 }
195
196 #[stable(feature = "rust1", since = "1.0.0")]
197 impl ToOwned for str {
198     type Owned = String;
199     fn to_owned(&self) -> String {
200         unsafe { String::from_utf8_unchecked(self.as_bytes().to_owned()) }
201     }
202 }
203
204 /// Methods for string slices.
205 #[lang = "str"]
206 #[cfg(not(test))]
207 impl str {
208     /// Returns the length of `self`.
209     ///
210     /// This length is in bytes, not [`char`]s or graphemes. In other words,
211     /// it may not be what a human considers the length of the string.
212     ///
213     /// [`char`]: primitive.char.html
214     ///
215     /// # Examples
216     ///
217     /// Basic usage:
218     ///
219     /// ```
220     /// let len = "foo".len();
221     /// assert_eq!(3, len);
222     ///
223     /// let len = "ƒoo".len(); // fancy f!
224     /// assert_eq!(4, len);
225     /// ```
226     #[stable(feature = "rust1", since = "1.0.0")]
227     #[inline]
228     pub fn len(&self) -> usize {
229         core_str::StrExt::len(self)
230     }
231
232     /// Returns `true` if `self` has a length of zero bytes.
233     ///
234     /// # Examples
235     ///
236     /// Basic usage:
237     ///
238     /// ```
239     /// let s = "";
240     /// assert!(s.is_empty());
241     ///
242     /// let s = "not empty";
243     /// assert!(!s.is_empty());
244     /// ```
245     #[inline]
246     #[stable(feature = "rust1", since = "1.0.0")]
247     pub fn is_empty(&self) -> bool {
248         core_str::StrExt::is_empty(self)
249     }
250
251     /// Checks that `index`-th byte lies at the start and/or end of a
252     /// UTF-8 code point sequence.
253     ///
254     /// The start and end of the string (when `index == self.len()`) are
255     /// considered to be
256     /// boundaries.
257     ///
258     /// Returns `false` if `index` is greater than `self.len()`.
259     ///
260     /// # Examples
261     ///
262     /// ```
263     /// let s = "Löwe 老虎 Léopard";
264     /// assert!(s.is_char_boundary(0));
265     /// // start of `老`
266     /// assert!(s.is_char_boundary(6));
267     /// assert!(s.is_char_boundary(s.len()));
268     ///
269     /// // second byte of `ö`
270     /// assert!(!s.is_char_boundary(2));
271     ///
272     /// // third byte of `老`
273     /// assert!(!s.is_char_boundary(8));
274     /// ```
275     #[stable(feature = "is_char_boundary", since = "1.9.0")]
276     #[inline]
277     pub fn is_char_boundary(&self, index: usize) -> bool {
278         core_str::StrExt::is_char_boundary(self, index)
279     }
280
281     /// Converts a string slice to a byte slice.
282     ///
283     /// # Examples
284     ///
285     /// Basic usage:
286     ///
287     /// ```
288     /// let bytes = "bors".as_bytes();
289     /// assert_eq!(b"bors", bytes);
290     /// ```
291     #[stable(feature = "rust1", since = "1.0.0")]
292     #[inline(always)]
293     pub fn as_bytes(&self) -> &[u8] {
294         core_str::StrExt::as_bytes(self)
295     }
296
297     /// Converts a mutable string slice to a mutable byte slice.
298     #[unstable(feature = "str_mut_extras", issue = "41119")]
299     #[inline(always)]
300     pub unsafe fn as_bytes_mut(&mut self) -> &mut [u8] {
301         core_str::StrExt::as_bytes_mut(self)
302     }
303
304     /// Converts a string slice to a raw pointer.
305     ///
306     /// As string slices are a slice of bytes, the raw pointer points to a
307     /// [`u8`]. This pointer will be pointing to the first byte of the string
308     /// slice.
309     ///
310     /// [`u8`]: primitive.u8.html
311     ///
312     /// # Examples
313     ///
314     /// Basic usage:
315     ///
316     /// ```
317     /// let s = "Hello";
318     /// let ptr = s.as_ptr();
319     /// ```
320     #[stable(feature = "rust1", since = "1.0.0")]
321     #[inline]
322     pub fn as_ptr(&self) -> *const u8 {
323         core_str::StrExt::as_ptr(self)
324     }
325
326     /// Returns a subslice of `str`.
327     ///
328     /// This is the non-panicking alternative to indexing the `str`. Returns `None` whenever
329     /// equivalent indexing operation would panic.
330     ///
331     /// # Examples
332     ///
333     /// ```
334     /// # #![feature(str_checked_slicing)]
335     /// let v = "🗻∈🌏";
336     /// assert_eq!(Some("🗻"), v.get(0..4));
337     /// assert!(v.get(1..).is_none());
338     /// assert!(v.get(..8).is_none());
339     /// assert!(v.get(..42).is_none());
340     /// ```
341     #[unstable(feature = "str_checked_slicing", issue = "39932")]
342     #[inline]
343     pub fn get<I: SliceIndex<str>>(&self, i: I) -> Option<&I::Output> {
344         core_str::StrExt::get(self, i)
345     }
346
347     /// Returns a mutable subslice of `str`.
348     ///
349     /// This is the non-panicking alternative to indexing the `str`. Returns `None` whenever
350     /// equivalent indexing operation would panic.
351     ///
352     /// # Examples
353     ///
354     /// ```
355     /// # #![feature(str_checked_slicing)]
356     /// let mut v = String::from("🗻∈🌏");
357     /// assert_eq!(Some("🗻"), v.get_mut(0..4).map(|v| &*v));
358     /// assert!(v.get_mut(1..).is_none());
359     /// assert!(v.get_mut(..8).is_none());
360     /// assert!(v.get_mut(..42).is_none());
361     /// ```
362     #[unstable(feature = "str_checked_slicing", issue = "39932")]
363     #[inline]
364     pub fn get_mut<I: SliceIndex<str>>(&mut self, i: I) -> Option<&mut I::Output> {
365         core_str::StrExt::get_mut(self, i)
366     }
367
368     /// Returns a unchecked subslice of `str`.
369     ///
370     /// This is the unchecked alternative to indexing the `str`.
371     ///
372     /// # Safety
373     ///
374     /// Callers of this function are responsible that these preconditions are
375     /// satisfied:
376     ///
377     /// * The starting index must come before the ending index;
378     /// * Indexes must be within bounds of the original slice;
379     /// * Indexes must lie on UTF-8 sequence boundaries.
380     ///
381     /// Failing that, the returned string slice may reference invalid memory or
382     /// violate the invariants communicated by the `str` type.
383     ///
384     /// # Examples
385     ///
386     /// ```
387     /// # #![feature(str_checked_slicing)]
388     /// let v = "🗻∈🌏";
389     /// unsafe {
390     ///     assert_eq!("🗻", v.get_unchecked(0..4));
391     ///     assert_eq!("∈", v.get_unchecked(4..7));
392     ///     assert_eq!("🌏", v.get_unchecked(7..11));
393     /// }
394     /// ```
395     #[unstable(feature = "str_checked_slicing", issue = "39932")]
396     #[inline]
397     pub unsafe fn get_unchecked<I: SliceIndex<str>>(&self, i: I) -> &I::Output {
398         core_str::StrExt::get_unchecked(self, i)
399     }
400
401     /// Returns a mutable, unchecked subslice of `str`.
402     ///
403     /// This is the unchecked alternative to indexing the `str`.
404     ///
405     /// # Safety
406     ///
407     /// Callers of this function are responsible that these preconditions are
408     /// satisfied:
409     ///
410     /// * The starting index must come before the ending index;
411     /// * Indexes must be within bounds of the original slice;
412     /// * Indexes must lie on UTF-8 sequence boundaries.
413     ///
414     /// Failing that, the returned string slice may reference invalid memory or
415     /// violate the invariants communicated by the `str` type.
416     ///
417     /// # Examples
418     ///
419     /// ```
420     /// # #![feature(str_checked_slicing)]
421     /// let mut v = String::from("🗻∈🌏");
422     /// unsafe {
423     ///     assert_eq!("🗻", v.get_unchecked_mut(0..4));
424     ///     assert_eq!("∈", v.get_unchecked_mut(4..7));
425     ///     assert_eq!("🌏", v.get_unchecked_mut(7..11));
426     /// }
427     /// ```
428     #[unstable(feature = "str_checked_slicing", issue = "39932")]
429     #[inline]
430     pub unsafe fn get_unchecked_mut<I: SliceIndex<str>>(&mut self, i: I) -> &mut I::Output {
431         core_str::StrExt::get_unchecked_mut(self, i)
432     }
433
434     /// Creates a string slice from another string slice, bypassing safety
435     /// checks.
436     ///
437     /// This new slice goes from `begin` to `end`, including `begin` but
438     /// excluding `end`.
439     ///
440     /// To get a mutable string slice instead, see the
441     /// [`slice_mut_unchecked`] method.
442     ///
443     /// [`slice_mut_unchecked`]: #method.slice_mut_unchecked
444     ///
445     /// # Safety
446     ///
447     /// Callers of this function are responsible that three preconditions are
448     /// satisfied:
449     ///
450     /// * `begin` must come before `end`.
451     /// * `begin` and `end` must be byte positions within the string slice.
452     /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
453     ///
454     /// # Examples
455     ///
456     /// Basic usage:
457     ///
458     /// ```
459     /// let s = "Löwe 老虎 Léopard";
460     ///
461     /// unsafe {
462     ///     assert_eq!("Löwe 老虎 Léopard", s.slice_unchecked(0, 21));
463     /// }
464     ///
465     /// let s = "Hello, world!";
466     ///
467     /// unsafe {
468     ///     assert_eq!("world", s.slice_unchecked(7, 12));
469     /// }
470     /// ```
471     #[stable(feature = "rust1", since = "1.0.0")]
472     #[inline]
473     pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str {
474         core_str::StrExt::slice_unchecked(self, begin, end)
475     }
476
477     /// Creates a string slice from another string slice, bypassing safety
478     /// checks.
479     ///
480     /// This new slice goes from `begin` to `end`, including `begin` but
481     /// excluding `end`.
482     ///
483     /// To get an immutable string slice instead, see the
484     /// [`slice_unchecked`] method.
485     ///
486     /// [`slice_unchecked`]: #method.slice_unchecked
487     ///
488     /// # Safety
489     ///
490     /// Callers of this function are responsible that three preconditions are
491     /// satisfied:
492     ///
493     /// * `begin` must come before `end`.
494     /// * `begin` and `end` must be byte positions within the string slice.
495     /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
496     #[stable(feature = "str_slice_mut", since = "1.5.0")]
497     #[inline]
498     pub unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str {
499         core_str::StrExt::slice_mut_unchecked(self, begin, end)
500     }
501
502     /// Divide one string slice into two at an index.
503     ///
504     /// The argument, `mid`, should be a byte offset from the start of the
505     /// string. It must also be on the boundary of a UTF-8 code point.
506     ///
507     /// The two slices returned go from the start of the string slice to `mid`,
508     /// and from `mid` to the end of the string slice.
509     ///
510     /// To get mutable string slices instead, see the [`split_at_mut`]
511     /// method.
512     ///
513     /// [`split_at_mut`]: #method.split_at_mut
514     ///
515     /// # Panics
516     ///
517     /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
518     /// beyond the last code point of the string slice.
519     ///
520     /// # Examples
521     ///
522     /// Basic usage:
523     ///
524     /// ```
525     /// let s = "Per Martin-Löf";
526     ///
527     /// let (first, last) = s.split_at(3);
528     ///
529     /// assert_eq!("Per", first);
530     /// assert_eq!(" Martin-Löf", last);
531     /// ```
532     #[inline]
533     #[stable(feature = "str_split_at", since = "1.4.0")]
534     pub fn split_at(&self, mid: usize) -> (&str, &str) {
535         core_str::StrExt::split_at(self, mid)
536     }
537
538     /// Divide one mutable string slice into two at an index.
539     ///
540     /// The argument, `mid`, should be a byte offset from the start of the
541     /// string. It must also be on the boundary of a UTF-8 code point.
542     ///
543     /// The two slices returned go from the start of the string slice to `mid`,
544     /// and from `mid` to the end of the string slice.
545     ///
546     /// To get immutable string slices instead, see the [`split_at`] method.
547     ///
548     /// [`split_at`]: #method.split_at
549     ///
550     /// # Panics
551     ///
552     /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
553     /// beyond the last code point of the string slice.
554     ///
555     /// # Examples
556     ///
557     /// Basic usage:
558     ///
559     /// ```
560     /// let mut s = "Per Martin-Löf".to_string();
561     ///
562     /// let (first, last) = s.split_at_mut(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_mut(&mut self, mid: usize) -> (&mut str, &mut str) {
570         core_str::StrExt::split_at_mut(self, mid)
571     }
572
573     /// Returns an iterator over the `char`s of a string slice.
574     ///
575     /// As a string slice consists of valid UTF-8, we can iterate through a
576     /// string slice by [`char`]. This method returns such an iterator.
577     ///
578     /// It's important to remember that [`char`] represents a Unicode Scalar
579     /// Value, and may not match your idea of what a 'character' is. Iteration
580     /// over grapheme clusters may be what you actually want.
581     ///
582     /// [`char`]: primitive.char.html
583     ///
584     /// # Examples
585     ///
586     /// Basic usage:
587     ///
588     /// ```
589     /// let word = "goodbye";
590     ///
591     /// let count = word.chars().count();
592     /// assert_eq!(7, count);
593     ///
594     /// let mut chars = word.chars();
595     ///
596     /// assert_eq!(Some('g'), chars.next());
597     /// assert_eq!(Some('o'), chars.next());
598     /// assert_eq!(Some('o'), chars.next());
599     /// assert_eq!(Some('d'), chars.next());
600     /// assert_eq!(Some('b'), chars.next());
601     /// assert_eq!(Some('y'), chars.next());
602     /// assert_eq!(Some('e'), chars.next());
603     ///
604     /// assert_eq!(None, chars.next());
605     /// ```
606     ///
607     /// Remember, [`char`]s may not match your human intuition about characters:
608     ///
609     /// ```
610     /// let y = "y̆";
611     ///
612     /// let mut chars = y.chars();
613     ///
614     /// assert_eq!(Some('y'), chars.next()); // not 'y̆'
615     /// assert_eq!(Some('\u{0306}'), chars.next());
616     ///
617     /// assert_eq!(None, chars.next());
618     /// ```
619     #[stable(feature = "rust1", since = "1.0.0")]
620     #[inline]
621     pub fn chars(&self) -> Chars {
622         core_str::StrExt::chars(self)
623     }
624     /// Returns an iterator over the [`char`]s of a string slice, and their
625     /// positions.
626     ///
627     /// As a string slice consists of valid UTF-8, we can iterate through a
628     /// string slice by [`char`]. This method returns an iterator of both
629     /// these [`char`]s, as well as their byte positions.
630     ///
631     /// The iterator yields tuples. The position is first, the [`char`] is
632     /// second.
633     ///
634     /// [`char`]: primitive.char.html
635     ///
636     /// # Examples
637     ///
638     /// Basic usage:
639     ///
640     /// ```
641     /// let word = "goodbye";
642     ///
643     /// let count = word.char_indices().count();
644     /// assert_eq!(7, count);
645     ///
646     /// let mut char_indices = word.char_indices();
647     ///
648     /// assert_eq!(Some((0, 'g')), char_indices.next());
649     /// assert_eq!(Some((1, 'o')), char_indices.next());
650     /// assert_eq!(Some((2, 'o')), char_indices.next());
651     /// assert_eq!(Some((3, 'd')), char_indices.next());
652     /// assert_eq!(Some((4, 'b')), char_indices.next());
653     /// assert_eq!(Some((5, 'y')), char_indices.next());
654     /// assert_eq!(Some((6, 'e')), char_indices.next());
655     ///
656     /// assert_eq!(None, char_indices.next());
657     /// ```
658     ///
659     /// Remember, [`char`]s may not match your human intuition about characters:
660     ///
661     /// ```
662     /// let y = "y̆";
663     ///
664     /// let mut char_indices = y.char_indices();
665     ///
666     /// assert_eq!(Some((0, 'y')), char_indices.next()); // not (0, 'y̆')
667     /// assert_eq!(Some((1, '\u{0306}')), char_indices.next());
668     ///
669     /// assert_eq!(None, char_indices.next());
670     /// ```
671     #[stable(feature = "rust1", since = "1.0.0")]
672     #[inline]
673     pub fn char_indices(&self) -> CharIndices {
674         core_str::StrExt::char_indices(self)
675     }
676
677     /// An iterator over the bytes of a string slice.
678     ///
679     /// As a string slice consists of a sequence of bytes, we can iterate
680     /// through a string slice by byte. This method returns such an iterator.
681     ///
682     /// # Examples
683     ///
684     /// Basic usage:
685     ///
686     /// ```
687     /// let mut bytes = "bors".bytes();
688     ///
689     /// assert_eq!(Some(b'b'), bytes.next());
690     /// assert_eq!(Some(b'o'), bytes.next());
691     /// assert_eq!(Some(b'r'), bytes.next());
692     /// assert_eq!(Some(b's'), bytes.next());
693     ///
694     /// assert_eq!(None, bytes.next());
695     /// ```
696     #[stable(feature = "rust1", since = "1.0.0")]
697     #[inline]
698     pub fn bytes(&self) -> Bytes {
699         core_str::StrExt::bytes(self)
700     }
701
702     /// Split a string slice by whitespace.
703     ///
704     /// The iterator returned will return string slices that are sub-slices of
705     /// the original string slice, separated by any amount of whitespace.
706     ///
707     /// 'Whitespace' is defined according to the terms of the Unicode Derived
708     /// Core Property `White_Space`.
709     ///
710     /// # Examples
711     ///
712     /// Basic usage:
713     ///
714     /// ```
715     /// let mut iter = "A few words".split_whitespace();
716     ///
717     /// assert_eq!(Some("A"), iter.next());
718     /// assert_eq!(Some("few"), iter.next());
719     /// assert_eq!(Some("words"), iter.next());
720     ///
721     /// assert_eq!(None, iter.next());
722     /// ```
723     ///
724     /// All kinds of whitespace are considered:
725     ///
726     /// ```
727     /// let mut iter = " Mary   had\ta\u{2009}little  \n\t lamb".split_whitespace();
728     /// assert_eq!(Some("Mary"), iter.next());
729     /// assert_eq!(Some("had"), iter.next());
730     /// assert_eq!(Some("a"), iter.next());
731     /// assert_eq!(Some("little"), iter.next());
732     /// assert_eq!(Some("lamb"), iter.next());
733     ///
734     /// assert_eq!(None, iter.next());
735     /// ```
736     #[stable(feature = "split_whitespace", since = "1.1.0")]
737     #[inline]
738     pub fn split_whitespace(&self) -> SplitWhitespace {
739         UnicodeStr::split_whitespace(self)
740     }
741
742     /// An iterator over the lines of a string, as string slices.
743     ///
744     /// Lines are ended with either a newline (`\n`) or a carriage return with
745     /// a line feed (`\r\n`).
746     ///
747     /// The final line ending is optional.
748     ///
749     /// # Examples
750     ///
751     /// Basic usage:
752     ///
753     /// ```
754     /// let text = "foo\r\nbar\n\nbaz\n";
755     /// let mut lines = text.lines();
756     ///
757     /// assert_eq!(Some("foo"), lines.next());
758     /// assert_eq!(Some("bar"), lines.next());
759     /// assert_eq!(Some(""), lines.next());
760     /// assert_eq!(Some("baz"), lines.next());
761     ///
762     /// assert_eq!(None, lines.next());
763     /// ```
764     ///
765     /// The final line ending isn't required:
766     ///
767     /// ```
768     /// let text = "foo\nbar\n\r\nbaz";
769     /// let mut lines = text.lines();
770     ///
771     /// assert_eq!(Some("foo"), lines.next());
772     /// assert_eq!(Some("bar"), lines.next());
773     /// assert_eq!(Some(""), lines.next());
774     /// assert_eq!(Some("baz"), lines.next());
775     ///
776     /// assert_eq!(None, lines.next());
777     /// ```
778     #[stable(feature = "rust1", since = "1.0.0")]
779     #[inline]
780     pub fn lines(&self) -> Lines {
781         core_str::StrExt::lines(self)
782     }
783
784     /// An iterator over the lines of a string.
785     #[stable(feature = "rust1", since = "1.0.0")]
786     #[rustc_deprecated(since = "1.4.0", reason = "use lines() instead now")]
787     #[inline]
788     #[allow(deprecated)]
789     pub fn lines_any(&self) -> LinesAny {
790         core_str::StrExt::lines_any(self)
791     }
792
793     /// Returns an iterator of `u16` over the string encoded as UTF-16.
794     #[stable(feature = "encode_utf16", since = "1.8.0")]
795     pub fn encode_utf16(&self) -> EncodeUtf16 {
796         EncodeUtf16 { encoder: Utf16Encoder::new(self[..].chars()) }
797     }
798
799     /// Returns `true` if the given pattern matches a sub-slice of
800     /// this string slice.
801     ///
802     /// Returns `false` if it does not.
803     ///
804     /// # Examples
805     ///
806     /// Basic usage:
807     ///
808     /// ```
809     /// let bananas = "bananas";
810     ///
811     /// assert!(bananas.contains("nana"));
812     /// assert!(!bananas.contains("apples"));
813     /// ```
814     #[stable(feature = "rust1", since = "1.0.0")]
815     pub fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
816         core_str::StrExt::contains(self, pat)
817     }
818
819     /// Returns `true` if the given pattern matches a prefix of this
820     /// string slice.
821     ///
822     /// Returns `false` if it does not.
823     ///
824     /// # Examples
825     ///
826     /// Basic usage:
827     ///
828     /// ```
829     /// let bananas = "bananas";
830     ///
831     /// assert!(bananas.starts_with("bana"));
832     /// assert!(!bananas.starts_with("nana"));
833     /// ```
834     #[stable(feature = "rust1", since = "1.0.0")]
835     pub fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
836         core_str::StrExt::starts_with(self, pat)
837     }
838
839     /// Returns `true` if the given pattern matches a suffix of this
840     /// string slice.
841     ///
842     /// Returns `false` if it does not.
843     ///
844     /// # Examples
845     ///
846     /// Basic usage:
847     ///
848     /// ```
849     /// let bananas = "bananas";
850     ///
851     /// assert!(bananas.ends_with("anas"));
852     /// assert!(!bananas.ends_with("nana"));
853     /// ```
854     #[stable(feature = "rust1", since = "1.0.0")]
855     pub fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool
856         where P::Searcher: ReverseSearcher<'a>
857     {
858         core_str::StrExt::ends_with(self, pat)
859     }
860
861     /// Returns the byte index of the first character of this string slice that
862     /// matches the pattern.
863     ///
864     /// Returns [`None`] if the pattern doesn't match.
865     ///
866     /// The pattern can be a `&str`, [`char`], or a closure that determines if
867     /// a character matches.
868     ///
869     /// [`char`]: primitive.char.html
870     /// [`None`]: option/enum.Option.html#variant.None
871     ///
872     /// # Examples
873     ///
874     /// Simple patterns:
875     ///
876     /// ```
877     /// let s = "Löwe 老虎 Léopard";
878     ///
879     /// assert_eq!(s.find('L'), Some(0));
880     /// assert_eq!(s.find('é'), Some(14));
881     /// assert_eq!(s.find("Léopard"), Some(13));
882     /// ```
883     ///
884     /// More complex patterns with closures:
885     ///
886     /// ```
887     /// let s = "Löwe 老虎 Léopard";
888     ///
889     /// assert_eq!(s.find(char::is_whitespace), Some(5));
890     /// assert_eq!(s.find(char::is_lowercase), Some(1));
891     /// ```
892     ///
893     /// Not finding the pattern:
894     ///
895     /// ```
896     /// let s = "Löwe 老虎 Léopard";
897     /// let x: &[_] = &['1', '2'];
898     ///
899     /// assert_eq!(s.find(x), None);
900     /// ```
901     #[stable(feature = "rust1", since = "1.0.0")]
902     pub fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
903         core_str::StrExt::find(self, pat)
904     }
905
906     /// Returns the byte index of the last character of this string slice that
907     /// matches the pattern.
908     ///
909     /// Returns [`None`] if the pattern doesn't match.
910     ///
911     /// The pattern can be a `&str`, [`char`], or a closure that determines if
912     /// a character matches.
913     ///
914     /// [`char`]: primitive.char.html
915     /// [`None`]: option/enum.Option.html#variant.None
916     ///
917     /// # Examples
918     ///
919     /// Simple patterns:
920     ///
921     /// ```
922     /// let s = "Löwe 老虎 Léopard";
923     ///
924     /// assert_eq!(s.rfind('L'), Some(13));
925     /// assert_eq!(s.rfind('é'), Some(14));
926     /// ```
927     ///
928     /// More complex patterns with closures:
929     ///
930     /// ```
931     /// let s = "Löwe 老虎 Léopard";
932     ///
933     /// assert_eq!(s.rfind(char::is_whitespace), Some(12));
934     /// assert_eq!(s.rfind(char::is_lowercase), Some(20));
935     /// ```
936     ///
937     /// Not finding the pattern:
938     ///
939     /// ```
940     /// let s = "Löwe 老虎 Léopard";
941     /// let x: &[_] = &['1', '2'];
942     ///
943     /// assert_eq!(s.rfind(x), None);
944     /// ```
945     #[stable(feature = "rust1", since = "1.0.0")]
946     pub fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>
947         where P::Searcher: ReverseSearcher<'a>
948     {
949         core_str::StrExt::rfind(self, pat)
950     }
951
952     /// An iterator over substrings of this string slice, separated by
953     /// characters matched by a pattern.
954     ///
955     /// The pattern can be a `&str`, [`char`], or a closure that determines the
956     /// split.
957     ///
958     /// # Iterator behavior
959     ///
960     /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
961     /// allows a reverse search and forward/reverse search yields the same
962     /// elements. This is true for, eg, [`char`] but not for `&str`.
963     ///
964     /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
965     ///
966     /// If the pattern allows a reverse search but its results might differ
967     /// from a forward search, the [`rsplit`] method can be used.
968     ///
969     /// [`char`]: primitive.char.html
970     /// [`rsplit`]: #method.rsplit
971     ///
972     /// # Examples
973     ///
974     /// Simple patterns:
975     ///
976     /// ```
977     /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
978     /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
979     ///
980     /// let v: Vec<&str> = "".split('X').collect();
981     /// assert_eq!(v, [""]);
982     ///
983     /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
984     /// assert_eq!(v, ["lion", "", "tiger", "leopard"]);
985     ///
986     /// let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
987     /// assert_eq!(v, ["lion", "tiger", "leopard"]);
988     ///
989     /// let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
990     /// assert_eq!(v, ["abc", "def", "ghi"]);
991     ///
992     /// let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
993     /// assert_eq!(v, ["lion", "tiger", "leopard"]);
994     /// ```
995     ///
996     /// A more complex pattern, using a closure:
997     ///
998     /// ```
999     /// let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
1000     /// assert_eq!(v, ["abc", "def", "ghi"]);
1001     /// ```
1002     ///
1003     /// If a string contains multiple contiguous separators, you will end up
1004     /// with empty strings in the output:
1005     ///
1006     /// ```
1007     /// let x = "||||a||b|c".to_string();
1008     /// let d: Vec<_> = x.split('|').collect();
1009     ///
1010     /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1011     /// ```
1012     ///
1013     /// Contiguous separators are separated by the empty string.
1014     ///
1015     /// ```
1016     /// let x = "(///)".to_string();
1017     /// let d: Vec<_> = x.split('/').collect();;
1018     ///
1019     /// assert_eq!(d, &["(", "", "", ")"]);
1020     /// ```
1021     ///
1022     /// Separators at the start or end of a string are neighbored
1023     /// by empty strings.
1024     ///
1025     /// ```
1026     /// let d: Vec<_> = "010".split("0").collect();
1027     /// assert_eq!(d, &["", "1", ""]);
1028     /// ```
1029     ///
1030     /// When the empty string is used as a separator, it separates
1031     /// every character in the string, along with the beginning
1032     /// and end of the string.
1033     ///
1034     /// ```
1035     /// let f: Vec<_> = "rust".split("").collect();
1036     /// assert_eq!(f, &["", "r", "u", "s", "t", ""]);
1037     /// ```
1038     ///
1039     /// Contiguous separators can lead to possibly surprising behavior
1040     /// when whitespace is used as the separator. This code is correct:
1041     ///
1042     /// ```
1043     /// let x = "    a  b c".to_string();
1044     /// let d: Vec<_> = x.split(' ').collect();
1045     ///
1046     /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1047     /// ```
1048     ///
1049     /// It does _not_ give you:
1050     ///
1051     /// ```,ignore
1052     /// assert_eq!(d, &["a", "b", "c"]);
1053     /// ```
1054     ///
1055     /// Use [`split_whitespace`] for this behavior.
1056     ///
1057     /// [`split_whitespace`]: #method.split_whitespace
1058     #[stable(feature = "rust1", since = "1.0.0")]
1059     pub fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> {
1060         core_str::StrExt::split(self, pat)
1061     }
1062
1063     /// An iterator over substrings of the given string slice, separated by
1064     /// characters matched by a pattern and yielded in reverse order.
1065     ///
1066     /// The pattern can be a `&str`, [`char`], or a closure that determines the
1067     /// split.
1068     ///
1069     /// [`char`]: primitive.char.html
1070     ///
1071     /// # Iterator behavior
1072     ///
1073     /// The returned iterator requires that the pattern supports a reverse
1074     /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1075     /// search yields the same elements.
1076     ///
1077     /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1078     ///
1079     /// For iterating from the front, the [`split`] method can be used.
1080     ///
1081     /// [`split`]: #method.split
1082     ///
1083     /// # Examples
1084     ///
1085     /// Simple patterns:
1086     ///
1087     /// ```
1088     /// let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
1089     /// assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);
1090     ///
1091     /// let v: Vec<&str> = "".rsplit('X').collect();
1092     /// assert_eq!(v, [""]);
1093     ///
1094     /// let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect();
1095     /// assert_eq!(v, ["leopard", "tiger", "", "lion"]);
1096     ///
1097     /// let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
1098     /// assert_eq!(v, ["leopard", "tiger", "lion"]);
1099     /// ```
1100     ///
1101     /// A more complex pattern, using a closure:
1102     ///
1103     /// ```
1104     /// let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect();
1105     /// assert_eq!(v, ["ghi", "def", "abc"]);
1106     /// ```
1107     #[stable(feature = "rust1", since = "1.0.0")]
1108     pub fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P>
1109         where P::Searcher: ReverseSearcher<'a>
1110     {
1111         core_str::StrExt::rsplit(self, pat)
1112     }
1113
1114     /// An iterator over substrings of the given string slice, separated by
1115     /// characters matched by a pattern.
1116     ///
1117     /// The pattern can be a `&str`, [`char`], or a closure that determines the
1118     /// split.
1119     ///
1120     /// Equivalent to [`split`], except that the trailing substring
1121     /// is skipped if empty.
1122     ///
1123     /// [`split`]: #method.split
1124     ///
1125     /// This method can be used for string data that is _terminated_,
1126     /// rather than _separated_ by a pattern.
1127     ///
1128     /// # Iterator behavior
1129     ///
1130     /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1131     /// allows a reverse search and forward/reverse search yields the same
1132     /// elements. This is true for, eg, [`char`] but not for `&str`.
1133     ///
1134     /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1135     /// [`char`]: primitive.char.html
1136     ///
1137     /// If the pattern allows a reverse search but its results might differ
1138     /// from a forward search, the [`rsplit_terminator`] method can be used.
1139     ///
1140     /// [`rsplit_terminator`]: #method.rsplit_terminator
1141     ///
1142     /// # Examples
1143     ///
1144     /// Basic usage:
1145     ///
1146     /// ```
1147     /// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
1148     /// assert_eq!(v, ["A", "B"]);
1149     ///
1150     /// let v: Vec<&str> = "A..B..".split_terminator(".").collect();
1151     /// assert_eq!(v, ["A", "", "B", ""]);
1152     /// ```
1153     #[stable(feature = "rust1", since = "1.0.0")]
1154     pub fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> {
1155         core_str::StrExt::split_terminator(self, pat)
1156     }
1157
1158     /// An iterator over substrings of `self`, separated by characters
1159     /// matched by a pattern and yielded in reverse order.
1160     ///
1161     /// The pattern can be a simple `&str`, [`char`], or a closure that
1162     /// determines the split.
1163     /// Additional libraries might provide more complex patterns like
1164     /// regular expressions.
1165     ///
1166     /// [`char`]: primitive.char.html
1167     ///
1168     /// Equivalent to [`split`], except that the trailing substring is
1169     /// skipped if empty.
1170     ///
1171     /// [`split`]: #method.split
1172     ///
1173     /// This method can be used for string data that is _terminated_,
1174     /// rather than _separated_ by a pattern.
1175     ///
1176     /// # Iterator behavior
1177     ///
1178     /// The returned iterator requires that the pattern supports a
1179     /// reverse search, and it will be double ended if a forward/reverse
1180     /// search yields the same elements.
1181     ///
1182     /// For iterating from the front, the [`split_terminator`] method can be
1183     /// used.
1184     ///
1185     /// [`split_terminator`]: #method.split_terminator
1186     ///
1187     /// # Examples
1188     ///
1189     /// ```
1190     /// let v: Vec<&str> = "A.B.".rsplit_terminator('.').collect();
1191     /// assert_eq!(v, ["B", "A"]);
1192     ///
1193     /// let v: Vec<&str> = "A..B..".rsplit_terminator(".").collect();
1194     /// assert_eq!(v, ["", "B", "", "A"]);
1195     /// ```
1196     #[stable(feature = "rust1", since = "1.0.0")]
1197     pub fn rsplit_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplitTerminator<'a, P>
1198         where P::Searcher: ReverseSearcher<'a>
1199     {
1200         core_str::StrExt::rsplit_terminator(self, pat)
1201     }
1202
1203     /// An iterator over substrings of the given string slice, separated by a
1204     /// pattern, restricted to returning at most `n` items.
1205     ///
1206     /// If `n` substrings are returned, the last substring (the `n`th substring)
1207     /// will contain the remainder of the string.
1208     ///
1209     /// The pattern can be a `&str`, [`char`], or a closure that determines the
1210     /// split.
1211     ///
1212     /// [`char`]: primitive.char.html
1213     ///
1214     /// # Iterator behavior
1215     ///
1216     /// The returned iterator will not be double ended, because it is
1217     /// not efficient to support.
1218     ///
1219     /// If the pattern allows a reverse search, the [`rsplitn`] method can be
1220     /// used.
1221     ///
1222     /// [`rsplitn`]: #method.rsplitn
1223     ///
1224     /// # Examples
1225     ///
1226     /// Simple patterns:
1227     ///
1228     /// ```
1229     /// let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect();
1230     /// assert_eq!(v, ["Mary", "had", "a little lambda"]);
1231     ///
1232     /// let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect();
1233     /// assert_eq!(v, ["lion", "", "tigerXleopard"]);
1234     ///
1235     /// let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect();
1236     /// assert_eq!(v, ["abcXdef"]);
1237     ///
1238     /// let v: Vec<&str> = "".splitn(1, 'X').collect();
1239     /// assert_eq!(v, [""]);
1240     /// ```
1241     ///
1242     /// A more complex pattern, using a closure:
1243     ///
1244     /// ```
1245     /// let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect();
1246     /// assert_eq!(v, ["abc", "defXghi"]);
1247     /// ```
1248     #[stable(feature = "rust1", since = "1.0.0")]
1249     pub fn splitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> SplitN<'a, P> {
1250         core_str::StrExt::splitn(self, n, pat)
1251     }
1252
1253     /// An iterator over substrings of this string slice, separated by a
1254     /// pattern, starting from the end of the string, restricted to returning
1255     /// at most `n` items.
1256     ///
1257     /// If `n` substrings are returned, the last substring (the `n`th substring)
1258     /// will contain the remainder of the string.
1259     ///
1260     /// The pattern can be a `&str`, [`char`], or a closure that
1261     /// determines the split.
1262     ///
1263     /// [`char`]: primitive.char.html
1264     ///
1265     /// # Iterator behavior
1266     ///
1267     /// The returned iterator will not be double ended, because it is not
1268     /// efficient to support.
1269     ///
1270     /// For splitting from the front, the [`splitn`] method can be used.
1271     ///
1272     /// [`splitn`]: #method.splitn
1273     ///
1274     /// # Examples
1275     ///
1276     /// Simple patterns:
1277     ///
1278     /// ```
1279     /// let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect();
1280     /// assert_eq!(v, ["lamb", "little", "Mary had a"]);
1281     ///
1282     /// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect();
1283     /// assert_eq!(v, ["leopard", "tiger", "lionX"]);
1284     ///
1285     /// let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect();
1286     /// assert_eq!(v, ["leopard", "lion::tiger"]);
1287     /// ```
1288     ///
1289     /// A more complex pattern, using a closure:
1290     ///
1291     /// ```
1292     /// let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect();
1293     /// assert_eq!(v, ["ghi", "abc1def"]);
1294     /// ```
1295     #[stable(feature = "rust1", since = "1.0.0")]
1296     pub fn rsplitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> RSplitN<'a, P>
1297         where P::Searcher: ReverseSearcher<'a>
1298     {
1299         core_str::StrExt::rsplitn(self, n, pat)
1300     }
1301
1302     /// An iterator over the matches of a pattern within the given string
1303     /// slice.
1304     ///
1305     /// The pattern can be a `&str`, [`char`], or a closure that
1306     /// determines if a character matches.
1307     ///
1308     /// [`char`]: primitive.char.html
1309     ///
1310     /// # Iterator behavior
1311     ///
1312     /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1313     /// allows a reverse search and forward/reverse search yields the same
1314     /// elements. This is true for, eg, [`char`] but not for `&str`.
1315     ///
1316     /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1317     /// [`char`]: primitive.char.html
1318     ///
1319     /// If the pattern allows a reverse search but its results might differ
1320     /// from a forward search, the [`rmatches`] method can be used.
1321     ///
1322     /// [`rmatches`]: #method.rmatches
1323     ///
1324     /// # Examples
1325     ///
1326     /// Basic usage:
1327     ///
1328     /// ```
1329     /// let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect();
1330     /// assert_eq!(v, ["abc", "abc", "abc"]);
1331     ///
1332     /// let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect();
1333     /// assert_eq!(v, ["1", "2", "3"]);
1334     /// ```
1335     #[stable(feature = "str_matches", since = "1.2.0")]
1336     pub fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P> {
1337         core_str::StrExt::matches(self, pat)
1338     }
1339
1340     /// An iterator over the matches of a pattern within this string slice,
1341     /// yielded in reverse order.
1342     ///
1343     /// The pattern can be a `&str`, [`char`], or a closure that determines if
1344     /// a character matches.
1345     ///
1346     /// [`char`]: primitive.char.html
1347     ///
1348     /// # Iterator behavior
1349     ///
1350     /// The returned iterator requires that the pattern supports a reverse
1351     /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1352     /// search yields the same elements.
1353     ///
1354     /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1355     ///
1356     /// For iterating from the front, the [`matches`] method can be used.
1357     ///
1358     /// [`matches`]: #method.matches
1359     ///
1360     /// # Examples
1361     ///
1362     /// Basic usage:
1363     ///
1364     /// ```
1365     /// let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect();
1366     /// assert_eq!(v, ["abc", "abc", "abc"]);
1367     ///
1368     /// let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect();
1369     /// assert_eq!(v, ["3", "2", "1"]);
1370     /// ```
1371     #[stable(feature = "str_matches", since = "1.2.0")]
1372     pub fn rmatches<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatches<'a, P>
1373         where P::Searcher: ReverseSearcher<'a>
1374     {
1375         core_str::StrExt::rmatches(self, pat)
1376     }
1377
1378     /// An iterator over the disjoint matches of a pattern within this string
1379     /// slice as well as the index that the match starts at.
1380     ///
1381     /// For matches of `pat` within `self` that overlap, only the indices
1382     /// corresponding to the first match are returned.
1383     ///
1384     /// The pattern can be a `&str`, [`char`], or a closure that determines
1385     /// if a character matches.
1386     ///
1387     /// [`char`]: primitive.char.html
1388     ///
1389     /// # Iterator behavior
1390     ///
1391     /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1392     /// allows a reverse search and forward/reverse search yields the same
1393     /// elements. This is true for, eg, [`char`] but not for `&str`.
1394     ///
1395     /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1396     ///
1397     /// If the pattern allows a reverse search but its results might differ
1398     /// from a forward search, the [`rmatch_indices`] method can be used.
1399     ///
1400     /// [`rmatch_indices`]: #method.rmatch_indices
1401     ///
1402     /// # Examples
1403     ///
1404     /// Basic usage:
1405     ///
1406     /// ```
1407     /// let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect();
1408     /// assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]);
1409     ///
1410     /// let v: Vec<_> = "1abcabc2".match_indices("abc").collect();
1411     /// assert_eq!(v, [(1, "abc"), (4, "abc")]);
1412     ///
1413     /// let v: Vec<_> = "ababa".match_indices("aba").collect();
1414     /// assert_eq!(v, [(0, "aba")]); // only the first `aba`
1415     /// ```
1416     #[stable(feature = "str_match_indices", since = "1.5.0")]
1417     pub fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
1418         core_str::StrExt::match_indices(self, pat)
1419     }
1420
1421     /// An iterator over the disjoint matches of a pattern within `self`,
1422     /// yielded in reverse order along with the index of the match.
1423     ///
1424     /// For matches of `pat` within `self` that overlap, only the indices
1425     /// corresponding to the last match are returned.
1426     ///
1427     /// The pattern can be a `&str`, [`char`], or a closure that determines if a
1428     /// character matches.
1429     ///
1430     /// [`char`]: primitive.char.html
1431     ///
1432     /// # Iterator behavior
1433     ///
1434     /// The returned iterator requires that the pattern supports a reverse
1435     /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1436     /// search yields the same elements.
1437     ///
1438     /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1439     ///
1440     /// For iterating from the front, the [`match_indices`] method can be used.
1441     ///
1442     /// [`match_indices`]: #method.match_indices
1443     ///
1444     /// # Examples
1445     ///
1446     /// Basic usage:
1447     ///
1448     /// ```
1449     /// let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
1450     /// assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]);
1451     ///
1452     /// let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect();
1453     /// assert_eq!(v, [(4, "abc"), (1, "abc")]);
1454     ///
1455     /// let v: Vec<_> = "ababa".rmatch_indices("aba").collect();
1456     /// assert_eq!(v, [(2, "aba")]); // only the last `aba`
1457     /// ```
1458     #[stable(feature = "str_match_indices", since = "1.5.0")]
1459     pub fn rmatch_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatchIndices<'a, P>
1460         where P::Searcher: ReverseSearcher<'a>
1461     {
1462         core_str::StrExt::rmatch_indices(self, pat)
1463     }
1464
1465     /// Returns a string slice with leading and trailing whitespace removed.
1466     ///
1467     /// 'Whitespace' is defined according to the terms of the Unicode Derived
1468     /// Core Property `White_Space`.
1469     ///
1470     /// # Examples
1471     ///
1472     /// Basic usage:
1473     ///
1474     /// ```
1475     /// let s = " Hello\tworld\t";
1476     ///
1477     /// assert_eq!("Hello\tworld", s.trim());
1478     /// ```
1479     #[stable(feature = "rust1", since = "1.0.0")]
1480     pub fn trim(&self) -> &str {
1481         UnicodeStr::trim(self)
1482     }
1483
1484     /// Returns a string slice with leading whitespace removed.
1485     ///
1486     /// 'Whitespace' is defined according to the terms of the Unicode Derived
1487     /// Core Property `White_Space`.
1488     ///
1489     /// # Text directionality
1490     ///
1491     /// A string is a sequence of bytes. 'Left' in this context means the first
1492     /// position of that byte string; for a language like Arabic or Hebrew
1493     /// which are 'right to left' rather than 'left to right', this will be
1494     /// the _right_ side, not the left.
1495     ///
1496     /// # Examples
1497     ///
1498     /// Basic usage:
1499     ///
1500     /// ```
1501     /// let s = " Hello\tworld\t";
1502     ///
1503     /// assert_eq!("Hello\tworld\t", s.trim_left());
1504     /// ```
1505     ///
1506     /// Directionality:
1507     ///
1508     /// ```
1509     /// let s = "  English";
1510     /// assert!(Some('E') == s.trim_left().chars().next());
1511     ///
1512     /// let s = "  עברית";
1513     /// assert!(Some('ע') == s.trim_left().chars().next());
1514     /// ```
1515     #[stable(feature = "rust1", since = "1.0.0")]
1516     pub fn trim_left(&self) -> &str {
1517         UnicodeStr::trim_left(self)
1518     }
1519
1520     /// Returns a string slice with trailing whitespace removed.
1521     ///
1522     /// 'Whitespace' is defined according to the terms of the Unicode Derived
1523     /// Core Property `White_Space`.
1524     ///
1525     /// # Text directionality
1526     ///
1527     /// A string is a sequence of bytes. 'Right' in this context means the last
1528     /// position of that byte string; for a language like Arabic or Hebrew
1529     /// which are 'right to left' rather than 'left to right', this will be
1530     /// the _left_ side, not the right.
1531     ///
1532     /// # Examples
1533     ///
1534     /// Basic usage:
1535     ///
1536     /// ```
1537     /// let s = " Hello\tworld\t";
1538     ///
1539     /// assert_eq!(" Hello\tworld", s.trim_right());
1540     /// ```
1541     ///
1542     /// Directionality:
1543     ///
1544     /// ```
1545     /// let s = "English  ";
1546     /// assert!(Some('h') == s.trim_right().chars().rev().next());
1547     ///
1548     /// let s = "עברית  ";
1549     /// assert!(Some('ת') == s.trim_right().chars().rev().next());
1550     /// ```
1551     #[stable(feature = "rust1", since = "1.0.0")]
1552     pub fn trim_right(&self) -> &str {
1553         UnicodeStr::trim_right(self)
1554     }
1555
1556     /// Returns a string slice with all prefixes and suffixes that match a
1557     /// pattern repeatedly removed.
1558     ///
1559     /// The pattern can be a [`char`] or a closure that determines if a
1560     /// character matches.
1561     ///
1562     /// [`char`]: primitive.char.html
1563     ///
1564     /// # Examples
1565     ///
1566     /// Simple patterns:
1567     ///
1568     /// ```
1569     /// assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
1570     /// assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");
1571     ///
1572     /// let x: &[_] = &['1', '2'];
1573     /// assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
1574     /// ```
1575     ///
1576     /// A more complex pattern, using a closure:
1577     ///
1578     /// ```
1579     /// assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
1580     /// ```
1581     #[stable(feature = "rust1", since = "1.0.0")]
1582     pub fn trim_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1583         where P::Searcher: DoubleEndedSearcher<'a>
1584     {
1585         core_str::StrExt::trim_matches(self, pat)
1586     }
1587
1588     /// Returns a string slice with all prefixes that match a pattern
1589     /// repeatedly removed.
1590     ///
1591     /// The pattern can be a `&str`, [`char`], or a closure that determines if
1592     /// a character matches.
1593     ///
1594     /// [`char`]: primitive.char.html
1595     ///
1596     /// # Text directionality
1597     ///
1598     /// A string is a sequence of bytes. 'Left' in this context means the first
1599     /// position of that byte string; for a language like Arabic or Hebrew
1600     /// which are 'right to left' rather than 'left to right', this will be
1601     /// the _right_ side, not the left.
1602     ///
1603     /// # Examples
1604     ///
1605     /// Basic usage:
1606     ///
1607     /// ```
1608     /// assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
1609     /// assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");
1610     ///
1611     /// let x: &[_] = &['1', '2'];
1612     /// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
1613     /// ```
1614     #[stable(feature = "rust1", since = "1.0.0")]
1615     pub fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
1616         core_str::StrExt::trim_left_matches(self, pat)
1617     }
1618
1619     /// Returns a string slice with all suffixes that match a pattern
1620     /// repeatedly removed.
1621     ///
1622     /// The pattern can be a `&str`, [`char`], or a closure that
1623     /// determines if a character matches.
1624     ///
1625     /// [`char`]: primitive.char.html
1626     ///
1627     /// # Text directionality
1628     ///
1629     /// A string is a sequence of bytes. 'Right' in this context means the last
1630     /// position of that byte string; for a language like Arabic or Hebrew
1631     /// which are 'right to left' rather than 'left to right', this will be
1632     /// the _left_ side, not the right.
1633     ///
1634     /// # Examples
1635     ///
1636     /// Simple patterns:
1637     ///
1638     /// ```
1639     /// assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
1640     /// assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");
1641     ///
1642     /// let x: &[_] = &['1', '2'];
1643     /// assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
1644     /// ```
1645     ///
1646     /// A more complex pattern, using a closure:
1647     ///
1648     /// ```
1649     /// assert_eq!("1fooX".trim_left_matches(|c| c == '1' || c == 'X'), "fooX");
1650     /// ```
1651     #[stable(feature = "rust1", since = "1.0.0")]
1652     pub fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
1653         where P::Searcher: ReverseSearcher<'a>
1654     {
1655         core_str::StrExt::trim_right_matches(self, pat)
1656     }
1657
1658     /// Parses this string slice into another type.
1659     ///
1660     /// Because `parse()` is so general, it can cause problems with type
1661     /// inference. As such, `parse()` is one of the few times you'll see
1662     /// the syntax affectionately known as the 'turbofish': `::<>`. This
1663     /// helps the inference algorithm understand specifically which type
1664     /// you're trying to parse into.
1665     ///
1666     /// `parse()` can parse any type that implements the [`FromStr`] trait.
1667     ///
1668     /// [`FromStr`]: str/trait.FromStr.html
1669     ///
1670     /// # Errors
1671     ///
1672     /// Will return [`Err`] if it's not possible to parse this string slice into
1673     /// the desired type.
1674     ///
1675     /// [`Err`]: str/trait.FromStr.html#associatedtype.Err
1676     ///
1677     /// # Example
1678     ///
1679     /// Basic usage
1680     ///
1681     /// ```
1682     /// let four: u32 = "4".parse().unwrap();
1683     ///
1684     /// assert_eq!(4, four);
1685     /// ```
1686     ///
1687     /// Using the 'turbofish' instead of annotating `four`:
1688     ///
1689     /// ```
1690     /// let four = "4".parse::<u32>();
1691     ///
1692     /// assert_eq!(Ok(4), four);
1693     /// ```
1694     ///
1695     /// Failing to parse:
1696     ///
1697     /// ```
1698     /// let nope = "j".parse::<u32>();
1699     ///
1700     /// assert!(nope.is_err());
1701     /// ```
1702     #[inline]
1703     #[stable(feature = "rust1", since = "1.0.0")]
1704     pub fn parse<F: FromStr>(&self) -> Result<F, F::Err> {
1705         core_str::StrExt::parse(self)
1706     }
1707
1708     /// Replaces all matches of a pattern with another string.
1709     ///
1710     /// `replace` creates a new [`String`], and copies the data from this string slice into it.
1711     /// While doing so, it attempts to find matches of a pattern. If it finds any, it
1712     /// replaces them with the replacement string slice.
1713     ///
1714     /// [`String`]: string/struct.String.html
1715     ///
1716     /// # Examples
1717     ///
1718     /// Basic usage:
1719     ///
1720     /// ```
1721     /// let s = "this is old";
1722     ///
1723     /// assert_eq!("this is new", s.replace("old", "new"));
1724     /// ```
1725     ///
1726     /// When the pattern doesn't match:
1727     ///
1728     /// ```
1729     /// let s = "this is old";
1730     /// assert_eq!(s, s.replace("cookie monster", "little lamb"));
1731     /// ```
1732     #[stable(feature = "rust1", since = "1.0.0")]
1733     pub fn replace<'a, P: Pattern<'a>>(&'a self, from: P, to: &str) -> String {
1734         let mut result = String::new();
1735         let mut last_end = 0;
1736         for (start, part) in self.match_indices(from) {
1737             result.push_str(unsafe { self.slice_unchecked(last_end, start) });
1738             result.push_str(to);
1739             last_end = start + part.len();
1740         }
1741         result.push_str(unsafe { self.slice_unchecked(last_end, self.len()) });
1742         result
1743     }
1744
1745     /// Replaces first N matches of a pattern with another string.
1746     ///
1747     /// `replacen` creates a new [`String`], and copies the data from this string slice into it.
1748     /// While doing so, it attempts to find matches of a pattern. If it finds any, it
1749     /// replaces them with the replacement string slice at most `N` times.
1750     ///
1751     /// [`String`]: string/struct.String.html
1752     ///
1753     /// # Examples
1754     ///
1755     /// Basic usage:
1756     ///
1757     /// ```
1758     /// let s = "foo foo 123 foo";
1759     /// assert_eq!("new new 123 foo", s.replacen("foo", "new", 2));
1760     /// assert_eq!("faa fao 123 foo", s.replacen('o', "a", 3));
1761     /// assert_eq!("foo foo new23 foo", s.replacen(char::is_numeric, "new", 1));
1762     /// ```
1763     ///
1764     /// When the pattern doesn't match:
1765     ///
1766     /// ```
1767     /// let s = "this is old";
1768     /// assert_eq!(s, s.replacen("cookie monster", "little lamb", 10));
1769     /// ```
1770     #[stable(feature = "str_replacen", since = "1.16.0")]
1771     pub fn replacen<'a, P: Pattern<'a>>(&'a self, pat: P, to: &str, count: usize) -> String {
1772         // Hope to reduce the times of re-allocation
1773         let mut result = String::with_capacity(32);
1774         let mut last_end = 0;
1775         for (start, part) in self.match_indices(pat).take(count) {
1776             result.push_str(unsafe { self.slice_unchecked(last_end, start) });
1777             result.push_str(to);
1778             last_end = start + part.len();
1779         }
1780         result.push_str(unsafe { self.slice_unchecked(last_end, self.len()) });
1781         result
1782     }
1783
1784     /// Returns the lowercase equivalent of this string slice, as a new [`String`].
1785     ///
1786     /// 'Lowercase' is defined according to the terms of the Unicode Derived Core Property
1787     /// `Lowercase`.
1788     ///
1789     /// Since some characters can expand into multiple characters when changing
1790     /// the case, this function returns a [`String`] instead of modifying the
1791     /// parameter in-place.
1792     ///
1793     /// [`String`]: string/struct.String.html
1794     ///
1795     /// # Examples
1796     ///
1797     /// Basic usage:
1798     ///
1799     /// ```
1800     /// let s = "HELLO";
1801     ///
1802     /// assert_eq!("hello", s.to_lowercase());
1803     /// ```
1804     ///
1805     /// A tricky example, with sigma:
1806     ///
1807     /// ```
1808     /// let sigma = "Σ";
1809     ///
1810     /// assert_eq!("σ", sigma.to_lowercase());
1811     ///
1812     /// // but at the end of a word, it's ς, not σ:
1813     /// let odysseus = "ὈΔΥΣΣΕΎΣ";
1814     ///
1815     /// assert_eq!("ὀδυσσεύς", odysseus.to_lowercase());
1816     /// ```
1817     ///
1818     /// Languages without case are not changed:
1819     ///
1820     /// ```
1821     /// let new_year = "农历新年";
1822     ///
1823     /// assert_eq!(new_year, new_year.to_lowercase());
1824     /// ```
1825     #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
1826     pub fn to_lowercase(&self) -> String {
1827         let mut s = String::with_capacity(self.len());
1828         for (i, c) in self[..].char_indices() {
1829             if c == 'Σ' {
1830                 // Σ maps to σ, except at the end of a word where it maps to ς.
1831                 // This is the only conditional (contextual) but language-independent mapping
1832                 // in `SpecialCasing.txt`,
1833                 // so hard-code it rather than have a generic "condition" mechanism.
1834                 // See https://github.com/rust-lang/rust/issues/26035
1835                 map_uppercase_sigma(self, i, &mut s)
1836             } else {
1837                 s.extend(c.to_lowercase());
1838             }
1839         }
1840         return s;
1841
1842         fn map_uppercase_sigma(from: &str, i: usize, to: &mut String) {
1843             // See http://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G33992
1844             // for the definition of `Final_Sigma`.
1845             debug_assert!('Σ'.len_utf8() == 2);
1846             let is_word_final = case_ignoreable_then_cased(from[..i].chars().rev()) &&
1847                                 !case_ignoreable_then_cased(from[i + 2..].chars());
1848             to.push_str(if is_word_final { "ς" } else { "σ" });
1849         }
1850
1851         fn case_ignoreable_then_cased<I: Iterator<Item = char>>(iter: I) -> bool {
1852             use std_unicode::derived_property::{Cased, Case_Ignorable};
1853             match iter.skip_while(|&c| Case_Ignorable(c)).next() {
1854                 Some(c) => Cased(c),
1855                 None => false,
1856             }
1857         }
1858     }
1859
1860     /// Returns the uppercase equivalent of this string slice, as a new [`String`].
1861     ///
1862     /// 'Uppercase' is defined according to the terms of the Unicode Derived Core Property
1863     /// `Uppercase`.
1864     ///
1865     /// Since some characters can expand into multiple characters when changing
1866     /// the case, this function returns a [`String`] instead of modifying the
1867     /// parameter in-place.
1868     ///
1869     /// [`String`]: string/struct.String.html
1870     ///
1871     /// # Examples
1872     ///
1873     /// Basic usage:
1874     ///
1875     /// ```
1876     /// let s = "hello";
1877     ///
1878     /// assert_eq!("HELLO", s.to_uppercase());
1879     /// ```
1880     ///
1881     /// Scripts without case are not changed:
1882     ///
1883     /// ```
1884     /// let new_year = "农历新年";
1885     ///
1886     /// assert_eq!(new_year, new_year.to_uppercase());
1887     /// ```
1888     #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
1889     pub fn to_uppercase(&self) -> String {
1890         let mut s = String::with_capacity(self.len());
1891         s.extend(self.chars().flat_map(|c| c.to_uppercase()));
1892         return s;
1893     }
1894
1895     /// Escapes each char in `s` with `char::escape_debug`.
1896     #[unstable(feature = "str_escape",
1897                reason = "return type may change to be an iterator",
1898                issue = "27791")]
1899     pub fn escape_debug(&self) -> String {
1900         self.chars().flat_map(|c| c.escape_debug()).collect()
1901     }
1902
1903     /// Escapes each char in `s` with `char::escape_default`.
1904     #[unstable(feature = "str_escape",
1905                reason = "return type may change to be an iterator",
1906                issue = "27791")]
1907     pub fn escape_default(&self) -> String {
1908         self.chars().flat_map(|c| c.escape_default()).collect()
1909     }
1910
1911     /// Escapes each char in `s` with `char::escape_unicode`.
1912     #[unstable(feature = "str_escape",
1913                reason = "return type may change to be an iterator",
1914                issue = "27791")]
1915     pub fn escape_unicode(&self) -> String {
1916         self.chars().flat_map(|c| c.escape_unicode()).collect()
1917     }
1918
1919     /// Converts a `Box<str>` into a [`String`] without copying or allocating.
1920     ///
1921     /// [`String`]: string/struct.String.html
1922     ///
1923     /// # Examples
1924     ///
1925     /// Basic usage:
1926     ///
1927     /// ```
1928     /// let string = String::from("birthday gift");
1929     /// let boxed_str = string.clone().into_boxed_str();
1930     ///
1931     /// assert_eq!(boxed_str.into_string(), string);
1932     /// ```
1933     #[stable(feature = "box_str", since = "1.4.0")]
1934     pub fn into_string(self: Box<str>) -> String {
1935         unsafe {
1936             let slice = mem::transmute::<Box<str>, Box<[u8]>>(self);
1937             String::from_utf8_unchecked(slice.into_vec())
1938         }
1939     }
1940
1941     /// Create a [`String`] by repeating a string `n` times.
1942     ///
1943     /// [`String`]: string/struct.String.html
1944     ///
1945     /// # Examples
1946     ///
1947     /// Basic usage:
1948     ///
1949     /// ```
1950     /// assert_eq!("abc".repeat(4), String::from("abcabcabcabc"));
1951     /// ```
1952     #[stable(feature = "repeat_str", since = "1.16.0")]
1953     pub fn repeat(&self, n: usize) -> String {
1954         let mut s = String::with_capacity(self.len() * n);
1955         s.extend((0..n).map(|_| self));
1956         s
1957     }
1958 }