]> git.lizzy.rs Git - rust.git/blob - library/alloc/src/string.rs
a34f530762d52fefa3b9ef6e3eba32111217e644
[rust.git] / library / alloc / src / string.rs
1 //! A UTF-8–encoded, growable string.
2 //!
3 //! This module contains the [`String`] type, the [`ToString`] trait for
4 //! converting to strings, and several error types that may result from
5 //! working with [`String`]s.
6 //!
7 //! # Examples
8 //!
9 //! There are multiple ways to create a new [`String`] from a string literal:
10 //!
11 //! ```
12 //! let s = "Hello".to_string();
13 //!
14 //! let s = String::from("world");
15 //! let s: String = "also this".into();
16 //! ```
17 //!
18 //! You can create a new [`String`] from an existing one by concatenating with
19 //! `+`:
20 //!
21 //! ```
22 //! let s = "Hello".to_string();
23 //!
24 //! let message = s + " world!";
25 //! ```
26 //!
27 //! If you have a vector of valid UTF-8 bytes, you can make a [`String`] out of
28 //! it. You can do the reverse too.
29 //!
30 //! ```
31 //! let sparkle_heart = vec![240, 159, 146, 150];
32 //!
33 //! // We know these bytes are valid, so we'll use `unwrap()`.
34 //! let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
35 //!
36 //! assert_eq!("💖", sparkle_heart);
37 //!
38 //! let bytes = sparkle_heart.into_bytes();
39 //!
40 //! assert_eq!(bytes, [240, 159, 146, 150]);
41 //! ```
42
43 #![stable(feature = "rust1", since = "1.0.0")]
44
45 #[cfg(not(no_global_oom_handling))]
46 use core::char::{decode_utf16, REPLACEMENT_CHARACTER};
47 use core::fmt;
48 use core::hash;
49 #[cfg(not(no_global_oom_handling))]
50 use core::iter::FromIterator;
51 use core::iter::{from_fn, FusedIterator};
52 #[cfg(not(no_global_oom_handling))]
53 use core::ops::Add;
54 #[cfg(not(no_global_oom_handling))]
55 use core::ops::AddAssign;
56 #[cfg(not(no_global_oom_handling))]
57 use core::ops::Bound::{Excluded, Included, Unbounded};
58 use core::ops::{self, Index, IndexMut, Range, RangeBounds};
59 use core::ptr;
60 use core::slice;
61 #[cfg(not(no_global_oom_handling))]
62 use core::str::lossy;
63 use core::str::pattern::Pattern;
64
65 #[cfg(not(no_global_oom_handling))]
66 use crate::borrow::{Cow, ToOwned};
67 use crate::boxed::Box;
68 use crate::collections::TryReserveError;
69 use crate::str::{self, Chars, Utf8Error};
70 #[cfg(not(no_global_oom_handling))]
71 use crate::str::{from_boxed_utf8_unchecked, FromStr};
72 use crate::vec::Vec;
73
74 /// A UTF-8–encoded, growable string.
75 ///
76 /// The `String` type is the most common string type that has ownership over the
77 /// contents of the string. It has a close relationship with its borrowed
78 /// counterpart, the primitive [`str`].
79 ///
80 /// # Examples
81 ///
82 /// You can create a `String` from [a literal string][`str`] with [`String::from`]:
83 ///
84 /// [`String::from`]: From::from
85 ///
86 /// ```
87 /// let hello = String::from("Hello, world!");
88 /// ```
89 ///
90 /// You can append a [`char`] to a `String` with the [`push`] method, and
91 /// append a [`&str`] with the [`push_str`] method:
92 ///
93 /// ```
94 /// let mut hello = String::from("Hello, ");
95 ///
96 /// hello.push('w');
97 /// hello.push_str("orld!");
98 /// ```
99 ///
100 /// [`push`]: String::push
101 /// [`push_str`]: String::push_str
102 ///
103 /// If you have a vector of UTF-8 bytes, you can create a `String` from it with
104 /// the [`from_utf8`] method:
105 ///
106 /// ```
107 /// // some bytes, in a vector
108 /// let sparkle_heart = vec![240, 159, 146, 150];
109 ///
110 /// // We know these bytes are valid, so we'll use `unwrap()`.
111 /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
112 ///
113 /// assert_eq!("💖", sparkle_heart);
114 /// ```
115 ///
116 /// [`from_utf8`]: String::from_utf8
117 ///
118 /// # UTF-8
119 ///
120 /// `String`s are always valid UTF-8. This has a few implications, the first of
121 /// which is that if you need a non-UTF-8 string, consider [`OsString`]. It is
122 /// similar, but without the UTF-8 constraint. The second implication is that
123 /// you cannot index into a `String`:
124 ///
125 /// ```compile_fail,E0277
126 /// let s = "hello";
127 ///
128 /// println!("The first letter of s is {}", s[0]); // ERROR!!!
129 /// ```
130 ///
131 /// [`OsString`]: ../../std/ffi/struct.OsString.html
132 ///
133 /// Indexing is intended to be a constant-time operation, but UTF-8 encoding
134 /// does not allow us to do this. Furthermore, it's not clear what sort of
135 /// thing the index should return: a byte, a codepoint, or a grapheme cluster.
136 /// The [`bytes`] and [`chars`] methods return iterators over the first
137 /// two, respectively.
138 ///
139 /// [`bytes`]: str::bytes
140 /// [`chars`]: str::chars
141 ///
142 /// # Deref
143 ///
144 /// `String`s implement [`Deref`]`<Target=str>`, and so inherit all of [`str`]'s
145 /// methods. In addition, this means that you can pass a `String` to a
146 /// function which takes a [`&str`] by using an ampersand (`&`):
147 ///
148 /// ```
149 /// fn takes_str(s: &str) { }
150 ///
151 /// let s = String::from("Hello");
152 ///
153 /// takes_str(&s);
154 /// ```
155 ///
156 /// This will create a [`&str`] from the `String` and pass it in. This
157 /// conversion is very inexpensive, and so generally, functions will accept
158 /// [`&str`]s as arguments unless they need a `String` for some specific
159 /// reason.
160 ///
161 /// In certain cases Rust doesn't have enough information to make this
162 /// conversion, known as [`Deref`] coercion. In the following example a string
163 /// slice [`&'a str`][`&str`] implements the trait `TraitExample`, and the function
164 /// `example_func` takes anything that implements the trait. In this case Rust
165 /// would need to make two implicit conversions, which Rust doesn't have the
166 /// means to do. For that reason, the following example will not compile.
167 ///
168 /// ```compile_fail,E0277
169 /// trait TraitExample {}
170 ///
171 /// impl<'a> TraitExample for &'a str {}
172 ///
173 /// fn example_func<A: TraitExample>(example_arg: A) {}
174 ///
175 /// let example_string = String::from("example_string");
176 /// example_func(&example_string);
177 /// ```
178 ///
179 /// There are two options that would work instead. The first would be to
180 /// change the line `example_func(&example_string);` to
181 /// `example_func(example_string.as_str());`, using the method [`as_str()`]
182 /// to explicitly extract the string slice containing the string. The second
183 /// way changes `example_func(&example_string);` to
184 /// `example_func(&*example_string);`. In this case we are dereferencing a
185 /// `String` to a [`str`][`&str`], then referencing the [`str`][`&str`] back to
186 /// [`&str`]. The second way is more idiomatic, however both work to do the
187 /// conversion explicitly rather than relying on the implicit conversion.
188 ///
189 /// # Representation
190 ///
191 /// A `String` is made up of three components: a pointer to some bytes, a
192 /// length, and a capacity. The pointer points to an internal buffer `String`
193 /// uses to store its data. The length is the number of bytes currently stored
194 /// in the buffer, and the capacity is the size of the buffer in bytes. As such,
195 /// the length will always be less than or equal to the capacity.
196 ///
197 /// This buffer is always stored on the heap.
198 ///
199 /// You can look at these with the [`as_ptr`], [`len`], and [`capacity`]
200 /// methods:
201 ///
202 /// ```
203 /// use std::mem;
204 ///
205 /// let story = String::from("Once upon a time...");
206 ///
207 // FIXME Update this when vec_into_raw_parts is stabilized
208 /// // Prevent automatically dropping the String's data
209 /// let mut story = mem::ManuallyDrop::new(story);
210 ///
211 /// let ptr = story.as_mut_ptr();
212 /// let len = story.len();
213 /// let capacity = story.capacity();
214 ///
215 /// // story has nineteen bytes
216 /// assert_eq!(19, len);
217 ///
218 /// // We can re-build a String out of ptr, len, and capacity. This is all
219 /// // unsafe because we are responsible for making sure the components are
220 /// // valid:
221 /// let s = unsafe { String::from_raw_parts(ptr, len, capacity) } ;
222 ///
223 /// assert_eq!(String::from("Once upon a time..."), s);
224 /// ```
225 ///
226 /// [`as_ptr`]: str::as_ptr
227 /// [`len`]: String::len
228 /// [`capacity`]: String::capacity
229 ///
230 /// If a `String` has enough capacity, adding elements to it will not
231 /// re-allocate. For example, consider this program:
232 ///
233 /// ```
234 /// let mut s = String::new();
235 ///
236 /// println!("{}", s.capacity());
237 ///
238 /// for _ in 0..5 {
239 ///     s.push_str("hello");
240 ///     println!("{}", s.capacity());
241 /// }
242 /// ```
243 ///
244 /// This will output the following:
245 ///
246 /// ```text
247 /// 0
248 /// 5
249 /// 10
250 /// 20
251 /// 20
252 /// 40
253 /// ```
254 ///
255 /// At first, we have no memory allocated at all, but as we append to the
256 /// string, it increases its capacity appropriately. If we instead use the
257 /// [`with_capacity`] method to allocate the correct capacity initially:
258 ///
259 /// ```
260 /// let mut s = String::with_capacity(25);
261 ///
262 /// println!("{}", s.capacity());
263 ///
264 /// for _ in 0..5 {
265 ///     s.push_str("hello");
266 ///     println!("{}", s.capacity());
267 /// }
268 /// ```
269 ///
270 /// [`with_capacity`]: String::with_capacity
271 ///
272 /// We end up with a different output:
273 ///
274 /// ```text
275 /// 25
276 /// 25
277 /// 25
278 /// 25
279 /// 25
280 /// 25
281 /// ```
282 ///
283 /// Here, there's no need to allocate more memory inside the loop.
284 ///
285 /// [`str`]: prim@str
286 /// [`&str`]: prim@str
287 /// [`Deref`]: core::ops::Deref
288 /// [`as_str()`]: String::as_str
289 #[derive(PartialOrd, Eq, Ord)]
290 #[cfg_attr(not(test), rustc_diagnostic_item = "string_type")]
291 #[stable(feature = "rust1", since = "1.0.0")]
292 pub struct String {
293     vec: Vec<u8>,
294 }
295
296 /// A possible error value when converting a `String` from a UTF-8 byte vector.
297 ///
298 /// This type is the error type for the [`from_utf8`] method on [`String`]. It
299 /// is designed in such a way to carefully avoid reallocations: the
300 /// [`into_bytes`] method will give back the byte vector that was used in the
301 /// conversion attempt.
302 ///
303 /// [`from_utf8`]: String::from_utf8
304 /// [`into_bytes`]: FromUtf8Error::into_bytes
305 ///
306 /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
307 /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
308 /// an analogue to `FromUtf8Error`, and you can get one from a `FromUtf8Error`
309 /// through the [`utf8_error`] method.
310 ///
311 /// [`Utf8Error`]: core::str::Utf8Error
312 /// [`std::str`]: core::str
313 /// [`&str`]: prim@str
314 /// [`utf8_error`]: Self::utf8_error
315 ///
316 /// # Examples
317 ///
318 /// Basic usage:
319 ///
320 /// ```
321 /// // some invalid bytes, in a vector
322 /// let bytes = vec![0, 159];
323 ///
324 /// let value = String::from_utf8(bytes);
325 ///
326 /// assert!(value.is_err());
327 /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
328 /// ```
329 #[stable(feature = "rust1", since = "1.0.0")]
330 #[cfg_attr(not(no_global_oom_handling), derive(Clone))]
331 #[derive(Debug, PartialEq, Eq)]
332 pub struct FromUtf8Error {
333     bytes: Vec<u8>,
334     error: Utf8Error,
335 }
336
337 /// A possible error value when converting a `String` from a UTF-16 byte slice.
338 ///
339 /// This type is the error type for the [`from_utf16`] method on [`String`].
340 ///
341 /// [`from_utf16`]: String::from_utf16
342 /// # Examples
343 ///
344 /// Basic usage:
345 ///
346 /// ```
347 /// // 𝄞mu<invalid>ic
348 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
349 ///           0xD800, 0x0069, 0x0063];
350 ///
351 /// assert!(String::from_utf16(v).is_err());
352 /// ```
353 #[stable(feature = "rust1", since = "1.0.0")]
354 #[derive(Debug)]
355 pub struct FromUtf16Error(());
356
357 impl String {
358     /// Creates a new empty `String`.
359     ///
360     /// Given that the `String` is empty, this will not allocate any initial
361     /// buffer. While that means that this initial operation is very
362     /// inexpensive, it may cause excessive allocation later when you add
363     /// data. If you have an idea of how much data the `String` will hold,
364     /// consider the [`with_capacity`] method to prevent excessive
365     /// re-allocation.
366     ///
367     /// [`with_capacity`]: String::with_capacity
368     ///
369     /// # Examples
370     ///
371     /// Basic usage:
372     ///
373     /// ```
374     /// let s = String::new();
375     /// ```
376     #[inline]
377     #[rustc_const_stable(feature = "const_string_new", since = "1.39.0")]
378     #[stable(feature = "rust1", since = "1.0.0")]
379     pub const fn new() -> String {
380         String { vec: Vec::new() }
381     }
382
383     /// Creates a new empty `String` with a particular capacity.
384     ///
385     /// `String`s have an internal buffer to hold their data. The capacity is
386     /// the length of that buffer, and can be queried with the [`capacity`]
387     /// method. This method creates an empty `String`, but one with an initial
388     /// buffer that can hold `capacity` bytes. This is useful when you may be
389     /// appending a bunch of data to the `String`, reducing the number of
390     /// reallocations it needs to do.
391     ///
392     /// [`capacity`]: String::capacity
393     ///
394     /// If the given capacity is `0`, no allocation will occur, and this method
395     /// is identical to the [`new`] method.
396     ///
397     /// [`new`]: String::new
398     ///
399     /// # Examples
400     ///
401     /// Basic usage:
402     ///
403     /// ```
404     /// let mut s = String::with_capacity(10);
405     ///
406     /// // The String contains no chars, even though it has capacity for more
407     /// assert_eq!(s.len(), 0);
408     ///
409     /// // These are all done without reallocating...
410     /// let cap = s.capacity();
411     /// for _ in 0..10 {
412     ///     s.push('a');
413     /// }
414     ///
415     /// assert_eq!(s.capacity(), cap);
416     ///
417     /// // ...but this may make the string reallocate
418     /// s.push('a');
419     /// ```
420     #[cfg(not(no_global_oom_handling))]
421     #[inline]
422     #[doc(alias = "alloc")]
423     #[doc(alias = "malloc")]
424     #[stable(feature = "rust1", since = "1.0.0")]
425     pub fn with_capacity(capacity: usize) -> String {
426         String { vec: Vec::with_capacity(capacity) }
427     }
428
429     // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
430     // required for this method definition, is not available. Since we don't
431     // require this method for testing purposes, I'll just stub it
432     // NB see the slice::hack module in slice.rs for more information
433     #[inline]
434     #[cfg(test)]
435     pub fn from_str(_: &str) -> String {
436         panic!("not available with cfg(test)");
437     }
438
439     /// Converts a vector of bytes to a `String`.
440     ///
441     /// A string ([`String`]) is made of bytes ([`u8`]), and a vector of bytes
442     /// ([`Vec<u8>`]) is made of bytes, so this function converts between the
443     /// two. Not all byte slices are valid `String`s, however: `String`
444     /// requires that it is valid UTF-8. `from_utf8()` checks to ensure that
445     /// the bytes are valid UTF-8, and then does the conversion.
446     ///
447     /// If you are sure that the byte slice is valid UTF-8, and you don't want
448     /// to incur the overhead of the validity check, there is an unsafe version
449     /// of this function, [`from_utf8_unchecked`], which has the same behavior
450     /// but skips the check.
451     ///
452     /// This method will take care to not copy the vector, for efficiency's
453     /// sake.
454     ///
455     /// If you need a [`&str`] instead of a `String`, consider
456     /// [`str::from_utf8`].
457     ///
458     /// The inverse of this method is [`into_bytes`].
459     ///
460     /// # Errors
461     ///
462     /// Returns [`Err`] if the slice is not UTF-8 with a description as to why the
463     /// provided bytes are not UTF-8. The vector you moved in is also included.
464     ///
465     /// # Examples
466     ///
467     /// Basic usage:
468     ///
469     /// ```
470     /// // some bytes, in a vector
471     /// let sparkle_heart = vec![240, 159, 146, 150];
472     ///
473     /// // We know these bytes are valid, so we'll use `unwrap()`.
474     /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
475     ///
476     /// assert_eq!("💖", sparkle_heart);
477     /// ```
478     ///
479     /// Incorrect bytes:
480     ///
481     /// ```
482     /// // some invalid bytes, in a vector
483     /// let sparkle_heart = vec![0, 159, 146, 150];
484     ///
485     /// assert!(String::from_utf8(sparkle_heart).is_err());
486     /// ```
487     ///
488     /// See the docs for [`FromUtf8Error`] for more details on what you can do
489     /// with this error.
490     ///
491     /// [`from_utf8_unchecked`]: String::from_utf8_unchecked
492     /// [`Vec<u8>`]: crate::vec::Vec
493     /// [`&str`]: prim@str
494     /// [`into_bytes`]: String::into_bytes
495     #[inline]
496     #[stable(feature = "rust1", since = "1.0.0")]
497     pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error> {
498         match str::from_utf8(&vec) {
499             Ok(..) => Ok(String { vec }),
500             Err(e) => Err(FromUtf8Error { bytes: vec, error: e }),
501         }
502     }
503
504     /// Converts a slice of bytes to a string, including invalid characters.
505     ///
506     /// Strings are made of bytes ([`u8`]), and a slice of bytes
507     /// ([`&[u8]`][byteslice]) is made of bytes, so this function converts
508     /// between the two. Not all byte slices are valid strings, however: strings
509     /// are required to be valid UTF-8. During this conversion,
510     /// `from_utf8_lossy()` will replace any invalid UTF-8 sequences with
511     /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD], which looks like this: �
512     ///
513     /// [byteslice]: prim@slice
514     /// [U+FFFD]: core::char::REPLACEMENT_CHARACTER
515     ///
516     /// If you are sure that the byte slice is valid UTF-8, and you don't want
517     /// to incur the overhead of the conversion, there is an unsafe version
518     /// of this function, [`from_utf8_unchecked`], which has the same behavior
519     /// but skips the checks.
520     ///
521     /// [`from_utf8_unchecked`]: String::from_utf8_unchecked
522     ///
523     /// This function returns a [`Cow<'a, str>`]. If our byte slice is invalid
524     /// UTF-8, then we need to insert the replacement characters, which will
525     /// change the size of the string, and hence, require a `String`. But if
526     /// it's already valid UTF-8, we don't need a new allocation. This return
527     /// type allows us to handle both cases.
528     ///
529     /// [`Cow<'a, str>`]: crate::borrow::Cow
530     ///
531     /// # Examples
532     ///
533     /// Basic usage:
534     ///
535     /// ```
536     /// // some bytes, in a vector
537     /// let sparkle_heart = vec![240, 159, 146, 150];
538     ///
539     /// let sparkle_heart = String::from_utf8_lossy(&sparkle_heart);
540     ///
541     /// assert_eq!("💖", sparkle_heart);
542     /// ```
543     ///
544     /// Incorrect bytes:
545     ///
546     /// ```
547     /// // some invalid bytes
548     /// let input = b"Hello \xF0\x90\x80World";
549     /// let output = String::from_utf8_lossy(input);
550     ///
551     /// assert_eq!("Hello �World", output);
552     /// ```
553     #[cfg(not(no_global_oom_handling))]
554     #[stable(feature = "rust1", since = "1.0.0")]
555     pub fn from_utf8_lossy(v: &[u8]) -> Cow<'_, str> {
556         let mut iter = lossy::Utf8Lossy::from_bytes(v).chunks();
557
558         let (first_valid, first_broken) = if let Some(chunk) = iter.next() {
559             let lossy::Utf8LossyChunk { valid, broken } = chunk;
560             if valid.len() == v.len() {
561                 debug_assert!(broken.is_empty());
562                 return Cow::Borrowed(valid);
563             }
564             (valid, broken)
565         } else {
566             return Cow::Borrowed("");
567         };
568
569         const REPLACEMENT: &str = "\u{FFFD}";
570
571         let mut res = String::with_capacity(v.len());
572         res.push_str(first_valid);
573         if !first_broken.is_empty() {
574             res.push_str(REPLACEMENT);
575         }
576
577         for lossy::Utf8LossyChunk { valid, broken } in iter {
578             res.push_str(valid);
579             if !broken.is_empty() {
580                 res.push_str(REPLACEMENT);
581             }
582         }
583
584         Cow::Owned(res)
585     }
586
587     /// Decode a UTF-16–encoded vector `v` into a `String`, returning [`Err`]
588     /// if `v` contains any invalid data.
589     ///
590     /// # Examples
591     ///
592     /// Basic usage:
593     ///
594     /// ```
595     /// // 𝄞music
596     /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
597     ///           0x0073, 0x0069, 0x0063];
598     /// assert_eq!(String::from("𝄞music"),
599     ///            String::from_utf16(v).unwrap());
600     ///
601     /// // 𝄞mu<invalid>ic
602     /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
603     ///           0xD800, 0x0069, 0x0063];
604     /// assert!(String::from_utf16(v).is_err());
605     /// ```
606     #[cfg(not(no_global_oom_handling))]
607     #[stable(feature = "rust1", since = "1.0.0")]
608     pub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error> {
609         // This isn't done via collect::<Result<_, _>>() for performance reasons.
610         // FIXME: the function can be simplified again when #48994 is closed.
611         let mut ret = String::with_capacity(v.len());
612         for c in decode_utf16(v.iter().cloned()) {
613             if let Ok(c) = c {
614                 ret.push(c);
615             } else {
616                 return Err(FromUtf16Error(()));
617             }
618         }
619         Ok(ret)
620     }
621
622     /// Decode a UTF-16–encoded slice `v` into a `String`, replacing
623     /// invalid data with [the replacement character (`U+FFFD`)][U+FFFD].
624     ///
625     /// Unlike [`from_utf8_lossy`] which returns a [`Cow<'a, str>`],
626     /// `from_utf16_lossy` returns a `String` since the UTF-16 to UTF-8
627     /// conversion requires a memory allocation.
628     ///
629     /// [`from_utf8_lossy`]: String::from_utf8_lossy
630     /// [`Cow<'a, str>`]: crate::borrow::Cow
631     /// [U+FFFD]: core::char::REPLACEMENT_CHARACTER
632     ///
633     /// # Examples
634     ///
635     /// Basic usage:
636     ///
637     /// ```
638     /// // 𝄞mus<invalid>ic<invalid>
639     /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
640     ///           0x0073, 0xDD1E, 0x0069, 0x0063,
641     ///           0xD834];
642     ///
643     /// assert_eq!(String::from("𝄞mus\u{FFFD}ic\u{FFFD}"),
644     ///            String::from_utf16_lossy(v));
645     /// ```
646     #[cfg(not(no_global_oom_handling))]
647     #[inline]
648     #[stable(feature = "rust1", since = "1.0.0")]
649     pub fn from_utf16_lossy(v: &[u16]) -> String {
650         decode_utf16(v.iter().cloned()).map(|r| r.unwrap_or(REPLACEMENT_CHARACTER)).collect()
651     }
652
653     /// Decomposes a `String` into its raw components.
654     ///
655     /// Returns the raw pointer to the underlying data, the length of
656     /// the string (in bytes), and the allocated capacity of the data
657     /// (in bytes). These are the same arguments in the same order as
658     /// the arguments to [`from_raw_parts`].
659     ///
660     /// After calling this function, the caller is responsible for the
661     /// memory previously managed by the `String`. The only way to do
662     /// this is to convert the raw pointer, length, and capacity back
663     /// into a `String` with the [`from_raw_parts`] function, allowing
664     /// the destructor to perform the cleanup.
665     ///
666     /// [`from_raw_parts`]: String::from_raw_parts
667     ///
668     /// # Examples
669     ///
670     /// ```
671     /// #![feature(vec_into_raw_parts)]
672     /// let s = String::from("hello");
673     ///
674     /// let (ptr, len, cap) = s.into_raw_parts();
675     ///
676     /// let rebuilt = unsafe { String::from_raw_parts(ptr, len, cap) };
677     /// assert_eq!(rebuilt, "hello");
678     /// ```
679     #[unstable(feature = "vec_into_raw_parts", reason = "new API", issue = "65816")]
680     pub fn into_raw_parts(self) -> (*mut u8, usize, usize) {
681         self.vec.into_raw_parts()
682     }
683
684     /// Creates a new `String` from a length, capacity, and pointer.
685     ///
686     /// # Safety
687     ///
688     /// This is highly unsafe, due to the number of invariants that aren't
689     /// checked:
690     ///
691     /// * The memory at `buf` needs to have been previously allocated by the
692     ///   same allocator the standard library uses, with a required alignment of exactly 1.
693     /// * `length` needs to be less than or equal to `capacity`.
694     /// * `capacity` needs to be the correct value.
695     /// * The first `length` bytes at `buf` need to be valid UTF-8.
696     ///
697     /// Violating these may cause problems like corrupting the allocator's
698     /// internal data structures.
699     ///
700     /// The ownership of `buf` is effectively transferred to the
701     /// `String` which may then deallocate, reallocate or change the
702     /// contents of memory pointed to by the pointer at will. Ensure
703     /// that nothing else uses the pointer after calling this
704     /// function.
705     ///
706     /// # Examples
707     ///
708     /// Basic usage:
709     ///
710     /// ```
711     /// use std::mem;
712     ///
713     /// unsafe {
714     ///     let s = String::from("hello");
715     ///
716     // FIXME Update this when vec_into_raw_parts is stabilized
717     ///     // Prevent automatically dropping the String's data
718     ///     let mut s = mem::ManuallyDrop::new(s);
719     ///
720     ///     let ptr = s.as_mut_ptr();
721     ///     let len = s.len();
722     ///     let capacity = s.capacity();
723     ///
724     ///     let s = String::from_raw_parts(ptr, len, capacity);
725     ///
726     ///     assert_eq!(String::from("hello"), s);
727     /// }
728     /// ```
729     #[inline]
730     #[stable(feature = "rust1", since = "1.0.0")]
731     pub unsafe fn from_raw_parts(buf: *mut u8, length: usize, capacity: usize) -> String {
732         unsafe { String { vec: Vec::from_raw_parts(buf, length, capacity) } }
733     }
734
735     /// Converts a vector of bytes to a `String` without checking that the
736     /// string contains valid UTF-8.
737     ///
738     /// See the safe version, [`from_utf8`], for more details.
739     ///
740     /// [`from_utf8`]: String::from_utf8
741     ///
742     /// # Safety
743     ///
744     /// This function is unsafe because it does not check that the bytes passed
745     /// to it are valid UTF-8. If this constraint is violated, it may cause
746     /// memory unsafety issues with future users of the `String`, as the rest of
747     /// the standard library assumes that `String`s are valid UTF-8.
748     ///
749     /// # Examples
750     ///
751     /// Basic usage:
752     ///
753     /// ```
754     /// // some bytes, in a vector
755     /// let sparkle_heart = vec![240, 159, 146, 150];
756     ///
757     /// let sparkle_heart = unsafe {
758     ///     String::from_utf8_unchecked(sparkle_heart)
759     /// };
760     ///
761     /// assert_eq!("💖", sparkle_heart);
762     /// ```
763     #[inline]
764     #[stable(feature = "rust1", since = "1.0.0")]
765     pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String {
766         String { vec: bytes }
767     }
768
769     /// Converts a `String` into a byte vector.
770     ///
771     /// This consumes the `String`, so we do not need to copy its contents.
772     ///
773     /// # Examples
774     ///
775     /// Basic usage:
776     ///
777     /// ```
778     /// let s = String::from("hello");
779     /// let bytes = s.into_bytes();
780     ///
781     /// assert_eq!(&[104, 101, 108, 108, 111][..], &bytes[..]);
782     /// ```
783     #[inline]
784     #[stable(feature = "rust1", since = "1.0.0")]
785     pub fn into_bytes(self) -> Vec<u8> {
786         self.vec
787     }
788
789     /// Extracts a string slice containing the entire `String`.
790     ///
791     /// # Examples
792     ///
793     /// Basic usage:
794     ///
795     /// ```
796     /// let s = String::from("foo");
797     ///
798     /// assert_eq!("foo", s.as_str());
799     /// ```
800     #[inline]
801     #[stable(feature = "string_as_str", since = "1.7.0")]
802     pub fn as_str(&self) -> &str {
803         self
804     }
805
806     /// Converts a `String` into a mutable string slice.
807     ///
808     /// # Examples
809     ///
810     /// Basic usage:
811     ///
812     /// ```
813     /// let mut s = String::from("foobar");
814     /// let s_mut_str = s.as_mut_str();
815     ///
816     /// s_mut_str.make_ascii_uppercase();
817     ///
818     /// assert_eq!("FOOBAR", s_mut_str);
819     /// ```
820     #[inline]
821     #[stable(feature = "string_as_str", since = "1.7.0")]
822     pub fn as_mut_str(&mut self) -> &mut str {
823         self
824     }
825
826     /// Appends a given string slice onto the end of this `String`.
827     ///
828     /// # Examples
829     ///
830     /// Basic usage:
831     ///
832     /// ```
833     /// let mut s = String::from("foo");
834     ///
835     /// s.push_str("bar");
836     ///
837     /// assert_eq!("foobar", s);
838     /// ```
839     #[cfg(not(no_global_oom_handling))]
840     #[inline]
841     #[stable(feature = "rust1", since = "1.0.0")]
842     pub fn push_str(&mut self, string: &str) {
843         self.vec.extend_from_slice(string.as_bytes())
844     }
845
846     /// Copies elements from `src` range to the end of the string.
847     ///
848     /// ## Panics
849     ///
850     /// Panics if the starting point or end point do not lie on a [`char`]
851     /// boundary, or if they're out of bounds.
852     ///
853     /// ## Examples
854     ///
855     /// ```
856     /// #![feature(string_extend_from_within)]
857     /// let mut string = String::from("abcde");
858     ///
859     /// string.extend_from_within(2..);
860     /// assert_eq!(string, "abcdecde");
861     ///
862     /// string.extend_from_within(..2);
863     /// assert_eq!(string, "abcdecdeab");
864     ///
865     /// string.extend_from_within(4..8);
866     /// assert_eq!(string, "abcdecdeabecde");
867     /// ```
868     #[cfg(not(no_global_oom_handling))]
869     #[unstable(feature = "string_extend_from_within", issue = "none")]
870     pub fn extend_from_within<R>(&mut self, src: R)
871     where
872         R: RangeBounds<usize>,
873     {
874         let src @ Range { start, end } = slice::range(src, ..self.len());
875
876         assert!(self.is_char_boundary(start));
877         assert!(self.is_char_boundary(end));
878
879         self.vec.extend_from_within(src);
880     }
881
882     /// Returns this `String`'s capacity, in bytes.
883     ///
884     /// # Examples
885     ///
886     /// Basic usage:
887     ///
888     /// ```
889     /// let s = String::with_capacity(10);
890     ///
891     /// assert!(s.capacity() >= 10);
892     /// ```
893     #[inline]
894     #[stable(feature = "rust1", since = "1.0.0")]
895     pub fn capacity(&self) -> usize {
896         self.vec.capacity()
897     }
898
899     /// Ensures that this `String`'s capacity is at least `additional` bytes
900     /// larger than its length.
901     ///
902     /// The capacity may be increased by more than `additional` bytes if it
903     /// chooses, to prevent frequent reallocations.
904     ///
905     /// If you do not want this "at least" behavior, see the [`reserve_exact`]
906     /// method.
907     ///
908     /// # Panics
909     ///
910     /// Panics if the new capacity overflows [`usize`].
911     ///
912     /// [`reserve_exact`]: String::reserve_exact
913     ///
914     /// # Examples
915     ///
916     /// Basic usage:
917     ///
918     /// ```
919     /// let mut s = String::new();
920     ///
921     /// s.reserve(10);
922     ///
923     /// assert!(s.capacity() >= 10);
924     /// ```
925     ///
926     /// This may not actually increase the capacity:
927     ///
928     /// ```
929     /// let mut s = String::with_capacity(10);
930     /// s.push('a');
931     /// s.push('b');
932     ///
933     /// // s now has a length of 2 and a capacity of 10
934     /// assert_eq!(2, s.len());
935     /// assert_eq!(10, s.capacity());
936     ///
937     /// // Since we already have an extra 8 capacity, calling this...
938     /// s.reserve(8);
939     ///
940     /// // ... doesn't actually increase.
941     /// assert_eq!(10, s.capacity());
942     /// ```
943     #[cfg(not(no_global_oom_handling))]
944     #[inline]
945     #[stable(feature = "rust1", since = "1.0.0")]
946     pub fn reserve(&mut self, additional: usize) {
947         self.vec.reserve(additional)
948     }
949
950     /// Ensures that this `String`'s capacity is `additional` bytes
951     /// larger than its length.
952     ///
953     /// Consider using the [`reserve`] method unless you absolutely know
954     /// better than the allocator.
955     ///
956     /// [`reserve`]: String::reserve
957     ///
958     /// # Panics
959     ///
960     /// Panics if the new capacity overflows `usize`.
961     ///
962     /// # Examples
963     ///
964     /// Basic usage:
965     ///
966     /// ```
967     /// let mut s = String::new();
968     ///
969     /// s.reserve_exact(10);
970     ///
971     /// assert!(s.capacity() >= 10);
972     /// ```
973     ///
974     /// This may not actually increase the capacity:
975     ///
976     /// ```
977     /// let mut s = String::with_capacity(10);
978     /// s.push('a');
979     /// s.push('b');
980     ///
981     /// // s now has a length of 2 and a capacity of 10
982     /// assert_eq!(2, s.len());
983     /// assert_eq!(10, s.capacity());
984     ///
985     /// // Since we already have an extra 8 capacity, calling this...
986     /// s.reserve_exact(8);
987     ///
988     /// // ... doesn't actually increase.
989     /// assert_eq!(10, s.capacity());
990     /// ```
991     #[cfg(not(no_global_oom_handling))]
992     #[inline]
993     #[stable(feature = "rust1", since = "1.0.0")]
994     pub fn reserve_exact(&mut self, additional: usize) {
995         self.vec.reserve_exact(additional)
996     }
997
998     /// Tries to reserve capacity for at least `additional` more elements to be inserted
999     /// in the given `String`. The collection may reserve more space to avoid
1000     /// frequent reallocations. After calling `reserve`, capacity will be
1001     /// greater than or equal to `self.len() + additional`. Does nothing if
1002     /// capacity is already sufficient.
1003     ///
1004     /// # Errors
1005     ///
1006     /// If the capacity overflows, or the allocator reports a failure, then an error
1007     /// is returned.
1008     ///
1009     /// # Examples
1010     ///
1011     /// ```
1012     /// #![feature(try_reserve)]
1013     /// use std::collections::TryReserveError;
1014     ///
1015     /// fn process_data(data: &str) -> Result<String, TryReserveError> {
1016     ///     let mut output = String::new();
1017     ///
1018     ///     // Pre-reserve the memory, exiting if we can't
1019     ///     output.try_reserve(data.len())?;
1020     ///
1021     ///     // Now we know this can't OOM in the middle of our complex work
1022     ///     output.push_str(data);
1023     ///
1024     ///     Ok(output)
1025     /// }
1026     /// # process_data("rust").expect("why is the test harness OOMing on 4 bytes?");
1027     /// ```
1028     #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
1029     pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
1030         self.vec.try_reserve(additional)
1031     }
1032
1033     /// Tries to reserve the minimum capacity for exactly `additional` more elements to
1034     /// be inserted in the given `String`. After calling `reserve_exact`,
1035     /// capacity will be greater than or equal to `self.len() + additional`.
1036     /// Does nothing if the capacity is already sufficient.
1037     ///
1038     /// Note that the allocator may give the collection more space than it
1039     /// requests. Therefore, capacity can not be relied upon to be precisely
1040     /// minimal. Prefer `reserve` if future insertions are expected.
1041     ///
1042     /// # Errors
1043     ///
1044     /// If the capacity overflows, or the allocator reports a failure, then an error
1045     /// is returned.
1046     ///
1047     /// # Examples
1048     ///
1049     /// ```
1050     /// #![feature(try_reserve)]
1051     /// use std::collections::TryReserveError;
1052     ///
1053     /// fn process_data(data: &str) -> Result<String, TryReserveError> {
1054     ///     let mut output = String::new();
1055     ///
1056     ///     // Pre-reserve the memory, exiting if we can't
1057     ///     output.try_reserve(data.len())?;
1058     ///
1059     ///     // Now we know this can't OOM in the middle of our complex work
1060     ///     output.push_str(data);
1061     ///
1062     ///     Ok(output)
1063     /// }
1064     /// # process_data("rust").expect("why is the test harness OOMing on 4 bytes?");
1065     /// ```
1066     #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
1067     pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
1068         self.vec.try_reserve_exact(additional)
1069     }
1070
1071     /// Shrinks the capacity of this `String` to match its length.
1072     ///
1073     /// # Examples
1074     ///
1075     /// Basic usage:
1076     ///
1077     /// ```
1078     /// let mut s = String::from("foo");
1079     ///
1080     /// s.reserve(100);
1081     /// assert!(s.capacity() >= 100);
1082     ///
1083     /// s.shrink_to_fit();
1084     /// assert_eq!(3, s.capacity());
1085     /// ```
1086     #[cfg(not(no_global_oom_handling))]
1087     #[inline]
1088     #[stable(feature = "rust1", since = "1.0.0")]
1089     pub fn shrink_to_fit(&mut self) {
1090         self.vec.shrink_to_fit()
1091     }
1092
1093     /// Shrinks the capacity of this `String` with a lower bound.
1094     ///
1095     /// The capacity will remain at least as large as both the length
1096     /// and the supplied value.
1097     ///
1098     /// If the current capacity is less than the lower limit, this is a no-op.
1099     ///
1100     /// # Examples
1101     ///
1102     /// ```
1103     /// #![feature(shrink_to)]
1104     /// let mut s = String::from("foo");
1105     ///
1106     /// s.reserve(100);
1107     /// assert!(s.capacity() >= 100);
1108     ///
1109     /// s.shrink_to(10);
1110     /// assert!(s.capacity() >= 10);
1111     /// s.shrink_to(0);
1112     /// assert!(s.capacity() >= 3);
1113     /// ```
1114     #[cfg(not(no_global_oom_handling))]
1115     #[inline]
1116     #[unstable(feature = "shrink_to", reason = "new API", issue = "56431")]
1117     pub fn shrink_to(&mut self, min_capacity: usize) {
1118         self.vec.shrink_to(min_capacity)
1119     }
1120
1121     /// Appends the given [`char`] to the end of this `String`.
1122     ///
1123     /// # Examples
1124     ///
1125     /// Basic usage:
1126     ///
1127     /// ```
1128     /// let mut s = String::from("abc");
1129     ///
1130     /// s.push('1');
1131     /// s.push('2');
1132     /// s.push('3');
1133     ///
1134     /// assert_eq!("abc123", s);
1135     /// ```
1136     #[cfg(not(no_global_oom_handling))]
1137     #[inline]
1138     #[stable(feature = "rust1", since = "1.0.0")]
1139     pub fn push(&mut self, ch: char) {
1140         match ch.len_utf8() {
1141             1 => self.vec.push(ch as u8),
1142             _ => self.vec.extend_from_slice(ch.encode_utf8(&mut [0; 4]).as_bytes()),
1143         }
1144     }
1145
1146     /// Returns a byte slice of this `String`'s contents.
1147     ///
1148     /// The inverse of this method is [`from_utf8`].
1149     ///
1150     /// [`from_utf8`]: String::from_utf8
1151     ///
1152     /// # Examples
1153     ///
1154     /// Basic usage:
1155     ///
1156     /// ```
1157     /// let s = String::from("hello");
1158     ///
1159     /// assert_eq!(&[104, 101, 108, 108, 111], s.as_bytes());
1160     /// ```
1161     #[inline]
1162     #[stable(feature = "rust1", since = "1.0.0")]
1163     pub fn as_bytes(&self) -> &[u8] {
1164         &self.vec
1165     }
1166
1167     /// Shortens this `String` to the specified length.
1168     ///
1169     /// If `new_len` is greater than the string's current length, this has no
1170     /// effect.
1171     ///
1172     /// Note that this method has no effect on the allocated capacity
1173     /// of the string
1174     ///
1175     /// # Panics
1176     ///
1177     /// Panics if `new_len` does not lie on a [`char`] boundary.
1178     ///
1179     /// # Examples
1180     ///
1181     /// Basic usage:
1182     ///
1183     /// ```
1184     /// let mut s = String::from("hello");
1185     ///
1186     /// s.truncate(2);
1187     ///
1188     /// assert_eq!("he", s);
1189     /// ```
1190     #[inline]
1191     #[stable(feature = "rust1", since = "1.0.0")]
1192     pub fn truncate(&mut self, new_len: usize) {
1193         if new_len <= self.len() {
1194             assert!(self.is_char_boundary(new_len));
1195             self.vec.truncate(new_len)
1196         }
1197     }
1198
1199     /// Removes the last character from the string buffer and returns it.
1200     ///
1201     /// Returns [`None`] if this `String` is empty.
1202     ///
1203     /// # Examples
1204     ///
1205     /// Basic usage:
1206     ///
1207     /// ```
1208     /// let mut s = String::from("foo");
1209     ///
1210     /// assert_eq!(s.pop(), Some('o'));
1211     /// assert_eq!(s.pop(), Some('o'));
1212     /// assert_eq!(s.pop(), Some('f'));
1213     ///
1214     /// assert_eq!(s.pop(), None);
1215     /// ```
1216     #[inline]
1217     #[stable(feature = "rust1", since = "1.0.0")]
1218     pub fn pop(&mut self) -> Option<char> {
1219         let ch = self.chars().rev().next()?;
1220         let newlen = self.len() - ch.len_utf8();
1221         unsafe {
1222             self.vec.set_len(newlen);
1223         }
1224         Some(ch)
1225     }
1226
1227     /// Removes a [`char`] from this `String` at a byte position and returns it.
1228     ///
1229     /// This is an *O*(*n*) operation, as it requires copying every element in the
1230     /// buffer.
1231     ///
1232     /// # Panics
1233     ///
1234     /// Panics if `idx` is larger than or equal to the `String`'s length,
1235     /// or if it does not lie on a [`char`] boundary.
1236     ///
1237     /// # Examples
1238     ///
1239     /// Basic usage:
1240     ///
1241     /// ```
1242     /// let mut s = String::from("foo");
1243     ///
1244     /// assert_eq!(s.remove(0), 'f');
1245     /// assert_eq!(s.remove(1), 'o');
1246     /// assert_eq!(s.remove(0), 'o');
1247     /// ```
1248     #[inline]
1249     #[stable(feature = "rust1", since = "1.0.0")]
1250     pub fn remove(&mut self, idx: usize) -> char {
1251         let ch = match self[idx..].chars().next() {
1252             Some(ch) => ch,
1253             None => panic!("cannot remove a char from the end of a string"),
1254         };
1255
1256         let next = idx + ch.len_utf8();
1257         let len = self.len();
1258         unsafe {
1259             ptr::copy(self.vec.as_ptr().add(next), self.vec.as_mut_ptr().add(idx), len - next);
1260             self.vec.set_len(len - (next - idx));
1261         }
1262         ch
1263     }
1264
1265     /// Remove all matches of pattern `pat` in the `String`.
1266     ///
1267     /// # Examples
1268     ///
1269     /// ```
1270     /// #![feature(string_remove_matches)]
1271     /// let mut s = String::from("Trees are not green, the sky is not blue.");
1272     /// s.remove_matches("not ");
1273     /// assert_eq!("Trees are green, the sky is blue.", s);
1274     /// ```
1275     ///
1276     /// Matches will be detected and removed iteratively, so in cases where
1277     /// patterns overlap, only the first pattern will be removed:
1278     ///
1279     /// ```
1280     /// #![feature(string_remove_matches)]
1281     /// let mut s = String::from("banana");
1282     /// s.remove_matches("ana");
1283     /// assert_eq!("bna", s);
1284     /// ```
1285     #[cfg(not(no_global_oom_handling))]
1286     #[unstable(feature = "string_remove_matches", reason = "new API", issue = "72826")]
1287     pub fn remove_matches<'a, P>(&'a mut self, pat: P)
1288     where
1289         P: for<'x> Pattern<'x>,
1290     {
1291         use core::str::pattern::Searcher;
1292
1293         let rejections = {
1294             let mut searcher = pat.into_searcher(self);
1295             // Per Searcher::next:
1296             //
1297             // A Match result needs to contain the whole matched pattern,
1298             // however Reject results may be split up into arbitrary many
1299             // adjacent fragments. Both ranges may have zero length.
1300             //
1301             // In practice the implementation of Searcher::next_match tends to
1302             // be more efficient, so we use it here and do some work to invert
1303             // matches into rejections since that's what we want to copy below.
1304             let mut front = 0;
1305             let rejections: Vec<_> = from_fn(|| {
1306                 let (start, end) = searcher.next_match()?;
1307                 let prev_front = front;
1308                 front = end;
1309                 Some((prev_front, start))
1310             })
1311             .collect();
1312             rejections.into_iter().chain(core::iter::once((front, self.len())))
1313         };
1314
1315         let mut len = 0;
1316         let ptr = self.vec.as_mut_ptr();
1317
1318         for (start, end) in rejections {
1319             let count = end - start;
1320             if start != len {
1321                 // SAFETY: per Searcher::next:
1322                 //
1323                 // The stream of Match and Reject values up to a Done will
1324                 // contain index ranges that are adjacent, non-overlapping,
1325                 // covering the whole haystack, and laying on utf8
1326                 // boundaries.
1327                 unsafe {
1328                     ptr::copy(ptr.add(start), ptr.add(len), count);
1329                 }
1330             }
1331             len += count;
1332         }
1333
1334         unsafe {
1335             self.vec.set_len(len);
1336         }
1337     }
1338
1339     /// Retains only the characters specified by the predicate.
1340     ///
1341     /// In other words, remove all characters `c` such that `f(c)` returns `false`.
1342     /// This method operates in place, visiting each character exactly once in the
1343     /// original order, and preserves the order of the retained characters.
1344     ///
1345     /// # Examples
1346     ///
1347     /// ```
1348     /// let mut s = String::from("f_o_ob_ar");
1349     ///
1350     /// s.retain(|c| c != '_');
1351     ///
1352     /// assert_eq!(s, "foobar");
1353     /// ```
1354     ///
1355     /// The exact order may be useful for tracking external state, like an index.
1356     ///
1357     /// ```
1358     /// let mut s = String::from("abcde");
1359     /// let keep = [false, true, true, false, true];
1360     /// let mut i = 0;
1361     /// s.retain(|_| (keep[i], i += 1).0);
1362     /// assert_eq!(s, "bce");
1363     /// ```
1364     #[inline]
1365     #[stable(feature = "string_retain", since = "1.26.0")]
1366     pub fn retain<F>(&mut self, mut f: F)
1367     where
1368         F: FnMut(char) -> bool,
1369     {
1370         struct SetLenOnDrop<'a> {
1371             s: &'a mut String,
1372             idx: usize,
1373             del_bytes: usize,
1374         }
1375
1376         impl<'a> Drop for SetLenOnDrop<'a> {
1377             fn drop(&mut self) {
1378                 let new_len = self.idx - self.del_bytes;
1379                 debug_assert!(new_len <= self.s.len());
1380                 unsafe { self.s.vec.set_len(new_len) };
1381             }
1382         }
1383
1384         let len = self.len();
1385         let mut guard = SetLenOnDrop { s: self, idx: 0, del_bytes: 0 };
1386
1387         while guard.idx < len {
1388             let ch = unsafe { guard.s.get_unchecked(guard.idx..len).chars().next().unwrap() };
1389             let ch_len = ch.len_utf8();
1390
1391             if !f(ch) {
1392                 guard.del_bytes += ch_len;
1393             } else if guard.del_bytes > 0 {
1394                 unsafe {
1395                     ptr::copy(
1396                         guard.s.vec.as_ptr().add(guard.idx),
1397                         guard.s.vec.as_mut_ptr().add(guard.idx - guard.del_bytes),
1398                         ch_len,
1399                     );
1400                 }
1401             }
1402
1403             // Point idx to the next char
1404             guard.idx += ch_len;
1405         }
1406
1407         drop(guard);
1408     }
1409
1410     /// Inserts a character into this `String` at a byte position.
1411     ///
1412     /// This is an *O*(*n*) operation as it requires copying every element in the
1413     /// buffer.
1414     ///
1415     /// # Panics
1416     ///
1417     /// Panics if `idx` is larger than the `String`'s length, or if it does not
1418     /// lie on a [`char`] boundary.
1419     ///
1420     /// # Examples
1421     ///
1422     /// Basic usage:
1423     ///
1424     /// ```
1425     /// let mut s = String::with_capacity(3);
1426     ///
1427     /// s.insert(0, 'f');
1428     /// s.insert(1, 'o');
1429     /// s.insert(2, 'o');
1430     ///
1431     /// assert_eq!("foo", s);
1432     /// ```
1433     #[cfg(not(no_global_oom_handling))]
1434     #[inline]
1435     #[stable(feature = "rust1", since = "1.0.0")]
1436     pub fn insert(&mut self, idx: usize, ch: char) {
1437         assert!(self.is_char_boundary(idx));
1438         let mut bits = [0; 4];
1439         let bits = ch.encode_utf8(&mut bits).as_bytes();
1440
1441         unsafe {
1442             self.insert_bytes(idx, bits);
1443         }
1444     }
1445
1446     #[cfg(not(no_global_oom_handling))]
1447     unsafe fn insert_bytes(&mut self, idx: usize, bytes: &[u8]) {
1448         let len = self.len();
1449         let amt = bytes.len();
1450         self.vec.reserve(amt);
1451
1452         unsafe {
1453             ptr::copy(self.vec.as_ptr().add(idx), self.vec.as_mut_ptr().add(idx + amt), len - idx);
1454             ptr::copy_nonoverlapping(bytes.as_ptr(), self.vec.as_mut_ptr().add(idx), amt);
1455             self.vec.set_len(len + amt);
1456         }
1457     }
1458
1459     /// Inserts a string slice into this `String` at a byte position.
1460     ///
1461     /// This is an *O*(*n*) operation as it requires copying every element in the
1462     /// buffer.
1463     ///
1464     /// # Panics
1465     ///
1466     /// Panics if `idx` is larger than the `String`'s length, or if it does not
1467     /// lie on a [`char`] boundary.
1468     ///
1469     /// # Examples
1470     ///
1471     /// Basic usage:
1472     ///
1473     /// ```
1474     /// let mut s = String::from("bar");
1475     ///
1476     /// s.insert_str(0, "foo");
1477     ///
1478     /// assert_eq!("foobar", s);
1479     /// ```
1480     #[cfg(not(no_global_oom_handling))]
1481     #[inline]
1482     #[stable(feature = "insert_str", since = "1.16.0")]
1483     pub fn insert_str(&mut self, idx: usize, string: &str) {
1484         assert!(self.is_char_boundary(idx));
1485
1486         unsafe {
1487             self.insert_bytes(idx, string.as_bytes());
1488         }
1489     }
1490
1491     /// Returns a mutable reference to the contents of this `String`.
1492     ///
1493     /// # Safety
1494     ///
1495     /// This function is unsafe because it does not check that the bytes passed
1496     /// to it are valid UTF-8. If this constraint is violated, it may cause
1497     /// memory unsafety issues with future users of the `String`, as the rest of
1498     /// the standard library assumes that `String`s are valid UTF-8.
1499     ///
1500     /// # Examples
1501     ///
1502     /// Basic usage:
1503     ///
1504     /// ```
1505     /// let mut s = String::from("hello");
1506     ///
1507     /// unsafe {
1508     ///     let vec = s.as_mut_vec();
1509     ///     assert_eq!(&[104, 101, 108, 108, 111][..], &vec[..]);
1510     ///
1511     ///     vec.reverse();
1512     /// }
1513     /// assert_eq!(s, "olleh");
1514     /// ```
1515     #[inline]
1516     #[stable(feature = "rust1", since = "1.0.0")]
1517     pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1518         &mut self.vec
1519     }
1520
1521     /// Returns the length of this `String`, in bytes, not [`char`]s or
1522     /// graphemes. In other words, it may not be what a human considers the
1523     /// length of the string.
1524     ///
1525     /// # Examples
1526     ///
1527     /// Basic usage:
1528     ///
1529     /// ```
1530     /// let a = String::from("foo");
1531     /// assert_eq!(a.len(), 3);
1532     ///
1533     /// let fancy_f = String::from("ƒoo");
1534     /// assert_eq!(fancy_f.len(), 4);
1535     /// assert_eq!(fancy_f.chars().count(), 3);
1536     /// ```
1537     #[doc(alias = "length")]
1538     #[inline]
1539     #[stable(feature = "rust1", since = "1.0.0")]
1540     pub fn len(&self) -> usize {
1541         self.vec.len()
1542     }
1543
1544     /// Returns `true` if this `String` has a length of zero, and `false` otherwise.
1545     ///
1546     /// # Examples
1547     ///
1548     /// Basic usage:
1549     ///
1550     /// ```
1551     /// let mut v = String::new();
1552     /// assert!(v.is_empty());
1553     ///
1554     /// v.push('a');
1555     /// assert!(!v.is_empty());
1556     /// ```
1557     #[inline]
1558     #[stable(feature = "rust1", since = "1.0.0")]
1559     pub fn is_empty(&self) -> bool {
1560         self.len() == 0
1561     }
1562
1563     /// Splits the string into two at the given byte index.
1564     ///
1565     /// Returns a newly allocated `String`. `self` contains bytes `[0, at)`, and
1566     /// the returned `String` contains bytes `[at, len)`. `at` must be on the
1567     /// boundary of a UTF-8 code point.
1568     ///
1569     /// Note that the capacity of `self` does not change.
1570     ///
1571     /// # Panics
1572     ///
1573     /// Panics if `at` is not on a `UTF-8` code point boundary, or if it is beyond the last
1574     /// code point of the string.
1575     ///
1576     /// # Examples
1577     ///
1578     /// ```
1579     /// # fn main() {
1580     /// let mut hello = String::from("Hello, World!");
1581     /// let world = hello.split_off(7);
1582     /// assert_eq!(hello, "Hello, ");
1583     /// assert_eq!(world, "World!");
1584     /// # }
1585     /// ```
1586     #[cfg(not(no_global_oom_handling))]
1587     #[inline]
1588     #[stable(feature = "string_split_off", since = "1.16.0")]
1589     #[must_use = "use `.truncate()` if you don't need the other half"]
1590     pub fn split_off(&mut self, at: usize) -> String {
1591         assert!(self.is_char_boundary(at));
1592         let other = self.vec.split_off(at);
1593         unsafe { String::from_utf8_unchecked(other) }
1594     }
1595
1596     /// Truncates this `String`, removing all contents.
1597     ///
1598     /// While this means the `String` will have a length of zero, it does not
1599     /// touch its capacity.
1600     ///
1601     /// # Examples
1602     ///
1603     /// Basic usage:
1604     ///
1605     /// ```
1606     /// let mut s = String::from("foo");
1607     ///
1608     /// s.clear();
1609     ///
1610     /// assert!(s.is_empty());
1611     /// assert_eq!(0, s.len());
1612     /// assert_eq!(3, s.capacity());
1613     /// ```
1614     #[inline]
1615     #[stable(feature = "rust1", since = "1.0.0")]
1616     pub fn clear(&mut self) {
1617         self.vec.clear()
1618     }
1619
1620     /// Creates a draining iterator that removes the specified range in the `String`
1621     /// and yields the removed `chars`.
1622     ///
1623     /// Note: The element range is removed even if the iterator is not
1624     /// consumed until the end.
1625     ///
1626     /// # Panics
1627     ///
1628     /// Panics if the starting point or end point do not lie on a [`char`]
1629     /// boundary, or if they're out of bounds.
1630     ///
1631     /// # Examples
1632     ///
1633     /// Basic usage:
1634     ///
1635     /// ```
1636     /// let mut s = String::from("α is alpha, β is beta");
1637     /// let beta_offset = s.find('β').unwrap_or(s.len());
1638     ///
1639     /// // Remove the range up until the β from the string
1640     /// let t: String = s.drain(..beta_offset).collect();
1641     /// assert_eq!(t, "α is alpha, ");
1642     /// assert_eq!(s, "β is beta");
1643     ///
1644     /// // A full range clears the string
1645     /// s.drain(..);
1646     /// assert_eq!(s, "");
1647     /// ```
1648     #[stable(feature = "drain", since = "1.6.0")]
1649     pub fn drain<R>(&mut self, range: R) -> Drain<'_>
1650     where
1651         R: RangeBounds<usize>,
1652     {
1653         // Memory safety
1654         //
1655         // The String version of Drain does not have the memory safety issues
1656         // of the vector version. The data is just plain bytes.
1657         // Because the range removal happens in Drop, if the Drain iterator is leaked,
1658         // the removal will not happen.
1659         let Range { start, end } = slice::range(range, ..self.len());
1660         assert!(self.is_char_boundary(start));
1661         assert!(self.is_char_boundary(end));
1662
1663         // Take out two simultaneous borrows. The &mut String won't be accessed
1664         // until iteration is over, in Drop.
1665         let self_ptr = self as *mut _;
1666         // SAFETY: `slice::range` and `is_char_boundary` do the appropriate bounds checks.
1667         let chars_iter = unsafe { self.get_unchecked(start..end) }.chars();
1668
1669         Drain { start, end, iter: chars_iter, string: self_ptr }
1670     }
1671
1672     /// Removes the specified range in the string,
1673     /// and replaces it with the given string.
1674     /// The given string doesn't need to be the same length as the range.
1675     ///
1676     /// # Panics
1677     ///
1678     /// Panics if the starting point or end point do not lie on a [`char`]
1679     /// boundary, or if they're out of bounds.
1680     ///
1681     /// # Examples
1682     ///
1683     /// Basic usage:
1684     ///
1685     /// ```
1686     /// let mut s = String::from("α is alpha, β is beta");
1687     /// let beta_offset = s.find('β').unwrap_or(s.len());
1688     ///
1689     /// // Replace the range up until the β from the string
1690     /// s.replace_range(..beta_offset, "Α is capital alpha; ");
1691     /// assert_eq!(s, "Α is capital alpha; β is beta");
1692     /// ```
1693     #[cfg(not(no_global_oom_handling))]
1694     #[stable(feature = "splice", since = "1.27.0")]
1695     pub fn replace_range<R>(&mut self, range: R, replace_with: &str)
1696     where
1697         R: RangeBounds<usize>,
1698     {
1699         // Memory safety
1700         //
1701         // Replace_range does not have the memory safety issues of a vector Splice.
1702         // of the vector version. The data is just plain bytes.
1703
1704         // WARNING: Inlining this variable would be unsound (#81138)
1705         let start = range.start_bound();
1706         match start {
1707             Included(&n) => assert!(self.is_char_boundary(n)),
1708             Excluded(&n) => assert!(self.is_char_boundary(n + 1)),
1709             Unbounded => {}
1710         };
1711         // WARNING: Inlining this variable would be unsound (#81138)
1712         let end = range.end_bound();
1713         match end {
1714             Included(&n) => assert!(self.is_char_boundary(n + 1)),
1715             Excluded(&n) => assert!(self.is_char_boundary(n)),
1716             Unbounded => {}
1717         };
1718
1719         // Using `range` again would be unsound (#81138)
1720         // We assume the bounds reported by `range` remain the same, but
1721         // an adversarial implementation could change between calls
1722         unsafe { self.as_mut_vec() }.splice((start, end), replace_with.bytes());
1723     }
1724
1725     /// Converts this `String` into a [`Box`]`<`[`str`]`>`.
1726     ///
1727     /// This will drop any excess capacity.
1728     ///
1729     /// [`str`]: prim@str
1730     ///
1731     /// # Examples
1732     ///
1733     /// Basic usage:
1734     ///
1735     /// ```
1736     /// let s = String::from("hello");
1737     ///
1738     /// let b = s.into_boxed_str();
1739     /// ```
1740     #[cfg(not(no_global_oom_handling))]
1741     #[stable(feature = "box_str", since = "1.4.0")]
1742     #[inline]
1743     pub fn into_boxed_str(self) -> Box<str> {
1744         let slice = self.vec.into_boxed_slice();
1745         unsafe { from_boxed_utf8_unchecked(slice) }
1746     }
1747 }
1748
1749 impl FromUtf8Error {
1750     /// Returns a slice of [`u8`]s bytes that were attempted to convert to a `String`.
1751     ///
1752     /// # Examples
1753     ///
1754     /// Basic usage:
1755     ///
1756     /// ```
1757     /// // some invalid bytes, in a vector
1758     /// let bytes = vec![0, 159];
1759     ///
1760     /// let value = String::from_utf8(bytes);
1761     ///
1762     /// assert_eq!(&[0, 159], value.unwrap_err().as_bytes());
1763     /// ```
1764     #[stable(feature = "from_utf8_error_as_bytes", since = "1.26.0")]
1765     pub fn as_bytes(&self) -> &[u8] {
1766         &self.bytes[..]
1767     }
1768
1769     /// Returns the bytes that were attempted to convert to a `String`.
1770     ///
1771     /// This method is carefully constructed to avoid allocation. It will
1772     /// consume the error, moving out the bytes, so that a copy of the bytes
1773     /// does not need to be made.
1774     ///
1775     /// # Examples
1776     ///
1777     /// Basic usage:
1778     ///
1779     /// ```
1780     /// // some invalid bytes, in a vector
1781     /// let bytes = vec![0, 159];
1782     ///
1783     /// let value = String::from_utf8(bytes);
1784     ///
1785     /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
1786     /// ```
1787     #[stable(feature = "rust1", since = "1.0.0")]
1788     pub fn into_bytes(self) -> Vec<u8> {
1789         self.bytes
1790     }
1791
1792     /// Fetch a `Utf8Error` to get more details about the conversion failure.
1793     ///
1794     /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
1795     /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
1796     /// an analogue to `FromUtf8Error`. See its documentation for more details
1797     /// on using it.
1798     ///
1799     /// [`std::str`]: core::str
1800     /// [`&str`]: prim@str
1801     ///
1802     /// # Examples
1803     ///
1804     /// Basic usage:
1805     ///
1806     /// ```
1807     /// // some invalid bytes, in a vector
1808     /// let bytes = vec![0, 159];
1809     ///
1810     /// let error = String::from_utf8(bytes).unwrap_err().utf8_error();
1811     ///
1812     /// // the first byte is invalid here
1813     /// assert_eq!(1, error.valid_up_to());
1814     /// ```
1815     #[stable(feature = "rust1", since = "1.0.0")]
1816     pub fn utf8_error(&self) -> Utf8Error {
1817         self.error
1818     }
1819 }
1820
1821 #[stable(feature = "rust1", since = "1.0.0")]
1822 impl fmt::Display for FromUtf8Error {
1823     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1824         fmt::Display::fmt(&self.error, f)
1825     }
1826 }
1827
1828 #[stable(feature = "rust1", since = "1.0.0")]
1829 impl fmt::Display for FromUtf16Error {
1830     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1831         fmt::Display::fmt("invalid utf-16: lone surrogate found", f)
1832     }
1833 }
1834
1835 #[cfg(not(no_global_oom_handling))]
1836 #[stable(feature = "rust1", since = "1.0.0")]
1837 impl Clone for String {
1838     fn clone(&self) -> Self {
1839         String { vec: self.vec.clone() }
1840     }
1841
1842     fn clone_from(&mut self, source: &Self) {
1843         self.vec.clone_from(&source.vec);
1844     }
1845 }
1846
1847 #[cfg(not(no_global_oom_handling))]
1848 #[stable(feature = "rust1", since = "1.0.0")]
1849 impl FromIterator<char> for String {
1850     fn from_iter<I: IntoIterator<Item = char>>(iter: I) -> String {
1851         let mut buf = String::new();
1852         buf.extend(iter);
1853         buf
1854     }
1855 }
1856
1857 #[cfg(not(no_global_oom_handling))]
1858 #[stable(feature = "string_from_iter_by_ref", since = "1.17.0")]
1859 impl<'a> FromIterator<&'a char> for String {
1860     fn from_iter<I: IntoIterator<Item = &'a char>>(iter: I) -> String {
1861         let mut buf = String::new();
1862         buf.extend(iter);
1863         buf
1864     }
1865 }
1866
1867 #[cfg(not(no_global_oom_handling))]
1868 #[stable(feature = "rust1", since = "1.0.0")]
1869 impl<'a> FromIterator<&'a str> for String {
1870     fn from_iter<I: IntoIterator<Item = &'a str>>(iter: I) -> String {
1871         let mut buf = String::new();
1872         buf.extend(iter);
1873         buf
1874     }
1875 }
1876
1877 #[cfg(not(no_global_oom_handling))]
1878 #[stable(feature = "extend_string", since = "1.4.0")]
1879 impl FromIterator<String> for String {
1880     fn from_iter<I: IntoIterator<Item = String>>(iter: I) -> String {
1881         let mut iterator = iter.into_iter();
1882
1883         // Because we're iterating over `String`s, we can avoid at least
1884         // one allocation by getting the first string from the iterator
1885         // and appending to it all the subsequent strings.
1886         match iterator.next() {
1887             None => String::new(),
1888             Some(mut buf) => {
1889                 buf.extend(iterator);
1890                 buf
1891             }
1892         }
1893     }
1894 }
1895
1896 #[cfg(not(no_global_oom_handling))]
1897 #[stable(feature = "box_str2", since = "1.45.0")]
1898 impl FromIterator<Box<str>> for String {
1899     fn from_iter<I: IntoIterator<Item = Box<str>>>(iter: I) -> String {
1900         let mut buf = String::new();
1901         buf.extend(iter);
1902         buf
1903     }
1904 }
1905
1906 #[cfg(not(no_global_oom_handling))]
1907 #[stable(feature = "herd_cows", since = "1.19.0")]
1908 impl<'a> FromIterator<Cow<'a, str>> for String {
1909     fn from_iter<I: IntoIterator<Item = Cow<'a, str>>>(iter: I) -> String {
1910         let mut iterator = iter.into_iter();
1911
1912         // Because we're iterating over CoWs, we can (potentially) avoid at least
1913         // one allocation by getting the first item and appending to it all the
1914         // subsequent items.
1915         match iterator.next() {
1916             None => String::new(),
1917             Some(cow) => {
1918                 let mut buf = cow.into_owned();
1919                 buf.extend(iterator);
1920                 buf
1921             }
1922         }
1923     }
1924 }
1925
1926 #[cfg(not(no_global_oom_handling))]
1927 #[stable(feature = "rust1", since = "1.0.0")]
1928 impl Extend<char> for String {
1929     fn extend<I: IntoIterator<Item = char>>(&mut self, iter: I) {
1930         let iterator = iter.into_iter();
1931         let (lower_bound, _) = iterator.size_hint();
1932         self.reserve(lower_bound);
1933         iterator.for_each(move |c| self.push(c));
1934     }
1935
1936     #[inline]
1937     fn extend_one(&mut self, c: char) {
1938         self.push(c);
1939     }
1940
1941     #[inline]
1942     fn extend_reserve(&mut self, additional: usize) {
1943         self.reserve(additional);
1944     }
1945 }
1946
1947 #[cfg(not(no_global_oom_handling))]
1948 #[stable(feature = "extend_ref", since = "1.2.0")]
1949 impl<'a> Extend<&'a char> for String {
1950     fn extend<I: IntoIterator<Item = &'a char>>(&mut self, iter: I) {
1951         self.extend(iter.into_iter().cloned());
1952     }
1953
1954     #[inline]
1955     fn extend_one(&mut self, &c: &'a char) {
1956         self.push(c);
1957     }
1958
1959     #[inline]
1960     fn extend_reserve(&mut self, additional: usize) {
1961         self.reserve(additional);
1962     }
1963 }
1964
1965 #[cfg(not(no_global_oom_handling))]
1966 #[stable(feature = "rust1", since = "1.0.0")]
1967 impl<'a> Extend<&'a str> for String {
1968     fn extend<I: IntoIterator<Item = &'a str>>(&mut self, iter: I) {
1969         iter.into_iter().for_each(move |s| self.push_str(s));
1970     }
1971
1972     #[inline]
1973     fn extend_one(&mut self, s: &'a str) {
1974         self.push_str(s);
1975     }
1976 }
1977
1978 #[cfg(not(no_global_oom_handling))]
1979 #[stable(feature = "box_str2", since = "1.45.0")]
1980 impl Extend<Box<str>> for String {
1981     fn extend<I: IntoIterator<Item = Box<str>>>(&mut self, iter: I) {
1982         iter.into_iter().for_each(move |s| self.push_str(&s));
1983     }
1984 }
1985
1986 #[cfg(not(no_global_oom_handling))]
1987 #[stable(feature = "extend_string", since = "1.4.0")]
1988 impl Extend<String> for String {
1989     fn extend<I: IntoIterator<Item = String>>(&mut self, iter: I) {
1990         iter.into_iter().for_each(move |s| self.push_str(&s));
1991     }
1992
1993     #[inline]
1994     fn extend_one(&mut self, s: String) {
1995         self.push_str(&s);
1996     }
1997 }
1998
1999 #[cfg(not(no_global_oom_handling))]
2000 #[stable(feature = "herd_cows", since = "1.19.0")]
2001 impl<'a> Extend<Cow<'a, str>> for String {
2002     fn extend<I: IntoIterator<Item = Cow<'a, str>>>(&mut self, iter: I) {
2003         iter.into_iter().for_each(move |s| self.push_str(&s));
2004     }
2005
2006     #[inline]
2007     fn extend_one(&mut self, s: Cow<'a, str>) {
2008         self.push_str(&s);
2009     }
2010 }
2011
2012 /// A convenience impl that delegates to the impl for `&str`.
2013 ///
2014 /// # Examples
2015 ///
2016 /// ```
2017 /// assert_eq!(String::from("Hello world").find("world"), Some(6));
2018 /// ```
2019 #[unstable(
2020     feature = "pattern",
2021     reason = "API not fully fleshed out and ready to be stabilized",
2022     issue = "27721"
2023 )]
2024 impl<'a, 'b> Pattern<'a> for &'b String {
2025     type Searcher = <&'b str as Pattern<'a>>::Searcher;
2026
2027     fn into_searcher(self, haystack: &'a str) -> <&'b str as Pattern<'a>>::Searcher {
2028         self[..].into_searcher(haystack)
2029     }
2030
2031     #[inline]
2032     fn is_contained_in(self, haystack: &'a str) -> bool {
2033         self[..].is_contained_in(haystack)
2034     }
2035
2036     #[inline]
2037     fn is_prefix_of(self, haystack: &'a str) -> bool {
2038         self[..].is_prefix_of(haystack)
2039     }
2040
2041     #[inline]
2042     fn strip_prefix_of(self, haystack: &'a str) -> Option<&'a str> {
2043         self[..].strip_prefix_of(haystack)
2044     }
2045
2046     #[inline]
2047     fn is_suffix_of(self, haystack: &'a str) -> bool {
2048         self[..].is_suffix_of(haystack)
2049     }
2050
2051     #[inline]
2052     fn strip_suffix_of(self, haystack: &'a str) -> Option<&'a str> {
2053         self[..].strip_suffix_of(haystack)
2054     }
2055 }
2056
2057 #[stable(feature = "rust1", since = "1.0.0")]
2058 impl PartialEq for String {
2059     #[inline]
2060     fn eq(&self, other: &String) -> bool {
2061         PartialEq::eq(&self[..], &other[..])
2062     }
2063     #[inline]
2064     fn ne(&self, other: &String) -> bool {
2065         PartialEq::ne(&self[..], &other[..])
2066     }
2067 }
2068
2069 macro_rules! impl_eq {
2070     ($lhs:ty, $rhs: ty) => {
2071         #[stable(feature = "rust1", since = "1.0.0")]
2072         #[allow(unused_lifetimes)]
2073         impl<'a, 'b> PartialEq<$rhs> for $lhs {
2074             #[inline]
2075             fn eq(&self, other: &$rhs) -> bool {
2076                 PartialEq::eq(&self[..], &other[..])
2077             }
2078             #[inline]
2079             fn ne(&self, other: &$rhs) -> bool {
2080                 PartialEq::ne(&self[..], &other[..])
2081             }
2082         }
2083
2084         #[stable(feature = "rust1", since = "1.0.0")]
2085         #[allow(unused_lifetimes)]
2086         impl<'a, 'b> PartialEq<$lhs> for $rhs {
2087             #[inline]
2088             fn eq(&self, other: &$lhs) -> bool {
2089                 PartialEq::eq(&self[..], &other[..])
2090             }
2091             #[inline]
2092             fn ne(&self, other: &$lhs) -> bool {
2093                 PartialEq::ne(&self[..], &other[..])
2094             }
2095         }
2096     };
2097 }
2098
2099 impl_eq! { String, str }
2100 impl_eq! { String, &'a str }
2101 #[cfg(not(no_global_oom_handling))]
2102 impl_eq! { Cow<'a, str>, str }
2103 #[cfg(not(no_global_oom_handling))]
2104 impl_eq! { Cow<'a, str>, &'b str }
2105 #[cfg(not(no_global_oom_handling))]
2106 impl_eq! { Cow<'a, str>, String }
2107
2108 #[stable(feature = "rust1", since = "1.0.0")]
2109 impl Default for String {
2110     /// Creates an empty `String`.
2111     #[inline]
2112     fn default() -> String {
2113         String::new()
2114     }
2115 }
2116
2117 #[stable(feature = "rust1", since = "1.0.0")]
2118 impl fmt::Display for String {
2119     #[inline]
2120     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2121         fmt::Display::fmt(&**self, f)
2122     }
2123 }
2124
2125 #[stable(feature = "rust1", since = "1.0.0")]
2126 impl fmt::Debug for String {
2127     #[inline]
2128     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2129         fmt::Debug::fmt(&**self, f)
2130     }
2131 }
2132
2133 #[stable(feature = "rust1", since = "1.0.0")]
2134 impl hash::Hash for String {
2135     #[inline]
2136     fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
2137         (**self).hash(hasher)
2138     }
2139 }
2140
2141 /// Implements the `+` operator for concatenating two strings.
2142 ///
2143 /// This consumes the `String` on the left-hand side and re-uses its buffer (growing it if
2144 /// necessary). This is done to avoid allocating a new `String` and copying the entire contents on
2145 /// every operation, which would lead to *O*(*n*^2) running time when building an *n*-byte string by
2146 /// repeated concatenation.
2147 ///
2148 /// The string on the right-hand side is only borrowed; its contents are copied into the returned
2149 /// `String`.
2150 ///
2151 /// # Examples
2152 ///
2153 /// Concatenating two `String`s takes the first by value and borrows the second:
2154 ///
2155 /// ```
2156 /// let a = String::from("hello");
2157 /// let b = String::from(" world");
2158 /// let c = a + &b;
2159 /// // `a` is moved and can no longer be used here.
2160 /// ```
2161 ///
2162 /// If you want to keep using the first `String`, you can clone it and append to the clone instead:
2163 ///
2164 /// ```
2165 /// let a = String::from("hello");
2166 /// let b = String::from(" world");
2167 /// let c = a.clone() + &b;
2168 /// // `a` is still valid here.
2169 /// ```
2170 ///
2171 /// Concatenating `&str` slices can be done by converting the first to a `String`:
2172 ///
2173 /// ```
2174 /// let a = "hello";
2175 /// let b = " world";
2176 /// let c = a.to_string() + b;
2177 /// ```
2178 #[cfg(not(no_global_oom_handling))]
2179 #[stable(feature = "rust1", since = "1.0.0")]
2180 impl Add<&str> for String {
2181     type Output = String;
2182
2183     #[inline]
2184     fn add(mut self, other: &str) -> String {
2185         self.push_str(other);
2186         self
2187     }
2188 }
2189
2190 /// Implements the `+=` operator for appending to a `String`.
2191 ///
2192 /// This has the same behavior as the [`push_str`][String::push_str] method.
2193 #[cfg(not(no_global_oom_handling))]
2194 #[stable(feature = "stringaddassign", since = "1.12.0")]
2195 impl AddAssign<&str> for String {
2196     #[inline]
2197     fn add_assign(&mut self, other: &str) {
2198         self.push_str(other);
2199     }
2200 }
2201
2202 #[stable(feature = "rust1", since = "1.0.0")]
2203 impl ops::Index<ops::Range<usize>> for String {
2204     type Output = str;
2205
2206     #[inline]
2207     fn index(&self, index: ops::Range<usize>) -> &str {
2208         &self[..][index]
2209     }
2210 }
2211 #[stable(feature = "rust1", since = "1.0.0")]
2212 impl ops::Index<ops::RangeTo<usize>> for String {
2213     type Output = str;
2214
2215     #[inline]
2216     fn index(&self, index: ops::RangeTo<usize>) -> &str {
2217         &self[..][index]
2218     }
2219 }
2220 #[stable(feature = "rust1", since = "1.0.0")]
2221 impl ops::Index<ops::RangeFrom<usize>> for String {
2222     type Output = str;
2223
2224     #[inline]
2225     fn index(&self, index: ops::RangeFrom<usize>) -> &str {
2226         &self[..][index]
2227     }
2228 }
2229 #[stable(feature = "rust1", since = "1.0.0")]
2230 impl ops::Index<ops::RangeFull> for String {
2231     type Output = str;
2232
2233     #[inline]
2234     fn index(&self, _index: ops::RangeFull) -> &str {
2235         unsafe { str::from_utf8_unchecked(&self.vec) }
2236     }
2237 }
2238 #[stable(feature = "inclusive_range", since = "1.26.0")]
2239 impl ops::Index<ops::RangeInclusive<usize>> for String {
2240     type Output = str;
2241
2242     #[inline]
2243     fn index(&self, index: ops::RangeInclusive<usize>) -> &str {
2244         Index::index(&**self, index)
2245     }
2246 }
2247 #[stable(feature = "inclusive_range", since = "1.26.0")]
2248 impl ops::Index<ops::RangeToInclusive<usize>> for String {
2249     type Output = str;
2250
2251     #[inline]
2252     fn index(&self, index: ops::RangeToInclusive<usize>) -> &str {
2253         Index::index(&**self, index)
2254     }
2255 }
2256
2257 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2258 impl ops::IndexMut<ops::Range<usize>> for String {
2259     #[inline]
2260     fn index_mut(&mut self, index: ops::Range<usize>) -> &mut str {
2261         &mut self[..][index]
2262     }
2263 }
2264 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2265 impl ops::IndexMut<ops::RangeTo<usize>> for String {
2266     #[inline]
2267     fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut str {
2268         &mut self[..][index]
2269     }
2270 }
2271 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2272 impl ops::IndexMut<ops::RangeFrom<usize>> for String {
2273     #[inline]
2274     fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut str {
2275         &mut self[..][index]
2276     }
2277 }
2278 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2279 impl ops::IndexMut<ops::RangeFull> for String {
2280     #[inline]
2281     fn index_mut(&mut self, _index: ops::RangeFull) -> &mut str {
2282         unsafe { str::from_utf8_unchecked_mut(&mut *self.vec) }
2283     }
2284 }
2285 #[stable(feature = "inclusive_range", since = "1.26.0")]
2286 impl ops::IndexMut<ops::RangeInclusive<usize>> for String {
2287     #[inline]
2288     fn index_mut(&mut self, index: ops::RangeInclusive<usize>) -> &mut str {
2289         IndexMut::index_mut(&mut **self, index)
2290     }
2291 }
2292 #[stable(feature = "inclusive_range", since = "1.26.0")]
2293 impl ops::IndexMut<ops::RangeToInclusive<usize>> for String {
2294     #[inline]
2295     fn index_mut(&mut self, index: ops::RangeToInclusive<usize>) -> &mut str {
2296         IndexMut::index_mut(&mut **self, index)
2297     }
2298 }
2299
2300 #[stable(feature = "rust1", since = "1.0.0")]
2301 impl ops::Deref for String {
2302     type Target = str;
2303
2304     #[inline]
2305     fn deref(&self) -> &str {
2306         unsafe { str::from_utf8_unchecked(&self.vec) }
2307     }
2308 }
2309
2310 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2311 impl ops::DerefMut for String {
2312     #[inline]
2313     fn deref_mut(&mut self) -> &mut str {
2314         unsafe { str::from_utf8_unchecked_mut(&mut *self.vec) }
2315     }
2316 }
2317
2318 /// A type alias for [`Infallible`].
2319 ///
2320 /// This alias exists for backwards compatibility, and may be eventually deprecated.
2321 ///
2322 /// [`Infallible`]: core::convert::Infallible
2323 #[stable(feature = "str_parse_error", since = "1.5.0")]
2324 pub type ParseError = core::convert::Infallible;
2325
2326 #[cfg(not(no_global_oom_handling))]
2327 #[stable(feature = "rust1", since = "1.0.0")]
2328 impl FromStr for String {
2329     type Err = core::convert::Infallible;
2330     #[inline]
2331     fn from_str(s: &str) -> Result<String, Self::Err> {
2332         Ok(String::from(s))
2333     }
2334 }
2335
2336 /// A trait for converting a value to a `String`.
2337 ///
2338 /// This trait is automatically implemented for any type which implements the
2339 /// [`Display`] trait. As such, `ToString` shouldn't be implemented directly:
2340 /// [`Display`] should be implemented instead, and you get the `ToString`
2341 /// implementation for free.
2342 ///
2343 /// [`Display`]: fmt::Display
2344 #[cfg_attr(not(test), rustc_diagnostic_item = "ToString")]
2345 #[stable(feature = "rust1", since = "1.0.0")]
2346 pub trait ToString {
2347     /// Converts the given value to a `String`.
2348     ///
2349     /// # Examples
2350     ///
2351     /// Basic usage:
2352     ///
2353     /// ```
2354     /// let i = 5;
2355     /// let five = String::from("5");
2356     ///
2357     /// assert_eq!(five, i.to_string());
2358     /// ```
2359     #[rustc_conversion_suggestion]
2360     #[stable(feature = "rust1", since = "1.0.0")]
2361     fn to_string(&self) -> String;
2362 }
2363
2364 /// # Panics
2365 ///
2366 /// In this implementation, the `to_string` method panics
2367 /// if the `Display` implementation returns an error.
2368 /// This indicates an incorrect `Display` implementation
2369 /// since `fmt::Write for String` never returns an error itself.
2370 #[cfg(not(no_global_oom_handling))]
2371 #[stable(feature = "rust1", since = "1.0.0")]
2372 impl<T: fmt::Display + ?Sized> ToString for T {
2373     // A common guideline is to not inline generic functions. However,
2374     // removing `#[inline]` from this method causes non-negligible regressions.
2375     // See <https://github.com/rust-lang/rust/pull/74852>, the last attempt
2376     // to try to remove it.
2377     #[inline]
2378     default fn to_string(&self) -> String {
2379         let mut buf = String::new();
2380         let mut formatter = core::fmt::Formatter::new(&mut buf);
2381         // Bypass format_args!() to avoid write_str with zero-length strs
2382         fmt::Display::fmt(self, &mut formatter)
2383             .expect("a Display implementation returned an error unexpectedly");
2384         buf
2385     }
2386 }
2387
2388 #[cfg(not(no_global_oom_handling))]
2389 #[stable(feature = "char_to_string_specialization", since = "1.46.0")]
2390 impl ToString for char {
2391     #[inline]
2392     fn to_string(&self) -> String {
2393         String::from(self.encode_utf8(&mut [0; 4]))
2394     }
2395 }
2396
2397 #[cfg(not(no_global_oom_handling))]
2398 #[stable(feature = "u8_to_string_specialization", since = "1.54.0")]
2399 impl ToString for u8 {
2400     #[inline]
2401     fn to_string(&self) -> String {
2402         let mut buf = String::with_capacity(3);
2403         let mut n = *self;
2404         if n >= 10 {
2405             if n >= 100 {
2406                 buf.push((b'0' + n / 100) as char);
2407                 n %= 100;
2408             }
2409             buf.push((b'0' + n / 10) as char);
2410             n %= 10;
2411         }
2412         buf.push((b'0' + n) as char);
2413         buf
2414     }
2415 }
2416
2417 #[cfg(not(no_global_oom_handling))]
2418 #[stable(feature = "i8_to_string_specialization", since = "1.54.0")]
2419 impl ToString for i8 {
2420     #[inline]
2421     fn to_string(&self) -> String {
2422         let mut buf = String::with_capacity(4);
2423         if self.is_negative() {
2424             buf.push('-');
2425         }
2426         let mut n = self.unsigned_abs();
2427         if n >= 10 {
2428             if n >= 100 {
2429                 buf.push('1');
2430                 n -= 100;
2431             }
2432             buf.push((b'0' + n / 10) as char);
2433             n %= 10;
2434         }
2435         buf.push((b'0' + n) as char);
2436         buf
2437     }
2438 }
2439
2440 #[cfg(not(no_global_oom_handling))]
2441 #[stable(feature = "str_to_string_specialization", since = "1.9.0")]
2442 impl ToString for str {
2443     #[inline]
2444     fn to_string(&self) -> String {
2445         String::from(self)
2446     }
2447 }
2448
2449 #[cfg(not(no_global_oom_handling))]
2450 #[stable(feature = "cow_str_to_string_specialization", since = "1.17.0")]
2451 impl ToString for Cow<'_, str> {
2452     #[inline]
2453     fn to_string(&self) -> String {
2454         self[..].to_owned()
2455     }
2456 }
2457
2458 #[cfg(not(no_global_oom_handling))]
2459 #[stable(feature = "string_to_string_specialization", since = "1.17.0")]
2460 impl ToString for String {
2461     #[inline]
2462     fn to_string(&self) -> String {
2463         self.to_owned()
2464     }
2465 }
2466
2467 #[stable(feature = "rust1", since = "1.0.0")]
2468 impl AsRef<str> for String {
2469     #[inline]
2470     fn as_ref(&self) -> &str {
2471         self
2472     }
2473 }
2474
2475 #[stable(feature = "string_as_mut", since = "1.43.0")]
2476 impl AsMut<str> for String {
2477     #[inline]
2478     fn as_mut(&mut self) -> &mut str {
2479         self
2480     }
2481 }
2482
2483 #[stable(feature = "rust1", since = "1.0.0")]
2484 impl AsRef<[u8]> for String {
2485     #[inline]
2486     fn as_ref(&self) -> &[u8] {
2487         self.as_bytes()
2488     }
2489 }
2490
2491 #[cfg(not(no_global_oom_handling))]
2492 #[stable(feature = "rust1", since = "1.0.0")]
2493 impl From<&str> for String {
2494     /// Converts a `&str` into a [`String`].
2495     ///
2496     /// The result is allocated on the heap.
2497     #[inline]
2498     fn from(s: &str) -> String {
2499         s.to_owned()
2500     }
2501 }
2502
2503 #[cfg(not(no_global_oom_handling))]
2504 #[stable(feature = "from_mut_str_for_string", since = "1.44.0")]
2505 impl From<&mut str> for String {
2506     /// Converts a `&mut str` into a [`String`].
2507     ///
2508     /// The result is allocated on the heap.
2509     #[inline]
2510     fn from(s: &mut str) -> String {
2511         s.to_owned()
2512     }
2513 }
2514
2515 #[cfg(not(no_global_oom_handling))]
2516 #[stable(feature = "from_ref_string", since = "1.35.0")]
2517 impl From<&String> for String {
2518     /// Converts a `&String` into a [`String`].
2519     ///
2520     /// This clones `s` and returns the clone.
2521     #[inline]
2522     fn from(s: &String) -> String {
2523         s.clone()
2524     }
2525 }
2526
2527 // note: test pulls in libstd, which causes errors here
2528 #[cfg(not(test))]
2529 #[stable(feature = "string_from_box", since = "1.18.0")]
2530 impl From<Box<str>> for String {
2531     /// Converts the given boxed `str` slice to a [`String`].
2532     /// It is notable that the `str` slice is owned.
2533     ///
2534     /// # Examples
2535     ///
2536     /// Basic usage:
2537     ///
2538     /// ```
2539     /// let s1: String = String::from("hello world");
2540     /// let s2: Box<str> = s1.into_boxed_str();
2541     /// let s3: String = String::from(s2);
2542     ///
2543     /// assert_eq!("hello world", s3)
2544     /// ```
2545     fn from(s: Box<str>) -> String {
2546         s.into_string()
2547     }
2548 }
2549
2550 #[cfg(not(no_global_oom_handling))]
2551 #[stable(feature = "box_from_str", since = "1.20.0")]
2552 impl From<String> for Box<str> {
2553     /// Converts the given [`String`] to a boxed `str` slice that is owned.
2554     ///
2555     /// # Examples
2556     ///
2557     /// Basic usage:
2558     ///
2559     /// ```
2560     /// let s1: String = String::from("hello world");
2561     /// let s2: Box<str> = Box::from(s1);
2562     /// let s3: String = String::from(s2);
2563     ///
2564     /// assert_eq!("hello world", s3)
2565     /// ```
2566     fn from(s: String) -> Box<str> {
2567         s.into_boxed_str()
2568     }
2569 }
2570
2571 #[cfg(not(no_global_oom_handling))]
2572 #[stable(feature = "string_from_cow_str", since = "1.14.0")]
2573 impl<'a> From<Cow<'a, str>> for String {
2574     /// Converts a clone-on-write string to an owned
2575     /// instance of [`String`].
2576     ///
2577     /// This extracts the owned string,
2578     /// clones the string if it is not already owned.
2579     ///
2580     /// # Example
2581     ///
2582     /// ```
2583     /// # use std::borrow::Cow;
2584     /// // If the string is not owned...
2585     /// let cow: Cow<str> = Cow::Borrowed("eggplant");
2586     /// // It will allocate on the heap and copy the string.
2587     /// let owned: String = String::from(cow);
2588     /// assert_eq!(&owned[..], "eggplant");
2589     /// ```
2590     fn from(s: Cow<'a, str>) -> String {
2591         s.into_owned()
2592     }
2593 }
2594
2595 #[cfg(not(no_global_oom_handling))]
2596 #[stable(feature = "rust1", since = "1.0.0")]
2597 impl<'a> From<&'a str> for Cow<'a, str> {
2598     /// Converts a string slice into a [`Borrowed`] variant.
2599     /// No heap allocation is performed, and the string
2600     /// is not copied.
2601     ///
2602     /// # Example
2603     ///
2604     /// ```
2605     /// # use std::borrow::Cow;
2606     /// assert_eq!(Cow::from("eggplant"), Cow::Borrowed("eggplant"));
2607     /// ```
2608     ///
2609     /// [`Borrowed`]: crate::borrow::Cow::Borrowed
2610     #[inline]
2611     fn from(s: &'a str) -> Cow<'a, str> {
2612         Cow::Borrowed(s)
2613     }
2614 }
2615
2616 #[cfg(not(no_global_oom_handling))]
2617 #[stable(feature = "rust1", since = "1.0.0")]
2618 impl<'a> From<String> for Cow<'a, str> {
2619     /// Converts a [`String`] into an [`Owned`] variant.
2620     /// No heap allocation is performed, and the string
2621     /// is not copied.
2622     ///
2623     /// # Example
2624     ///
2625     /// ```
2626     /// # use std::borrow::Cow;
2627     /// let s = "eggplant".to_string();
2628     /// let s2 = "eggplant".to_string();
2629     /// assert_eq!(Cow::from(s), Cow::<'static, str>::Owned(s2));
2630     /// ```
2631     ///
2632     /// [`Owned`]: crate::borrow::Cow::Owned
2633     #[inline]
2634     fn from(s: String) -> Cow<'a, str> {
2635         Cow::Owned(s)
2636     }
2637 }
2638
2639 #[cfg(not(no_global_oom_handling))]
2640 #[stable(feature = "cow_from_string_ref", since = "1.28.0")]
2641 impl<'a> From<&'a String> for Cow<'a, str> {
2642     /// Converts a [`String`] reference into a [`Borrowed`] variant.
2643     /// No heap allocation is performed, and the string
2644     /// is not copied.
2645     ///
2646     /// # Example
2647     ///
2648     /// ```
2649     /// # use std::borrow::Cow;
2650     /// let s = "eggplant".to_string();
2651     /// assert_eq!(Cow::from(&s), Cow::Borrowed("eggplant"));
2652     /// ```
2653     ///
2654     /// [`Borrowed`]: crate::borrow::Cow::Borrowed
2655     #[inline]
2656     fn from(s: &'a String) -> Cow<'a, str> {
2657         Cow::Borrowed(s.as_str())
2658     }
2659 }
2660
2661 #[cfg(not(no_global_oom_handling))]
2662 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2663 impl<'a> FromIterator<char> for Cow<'a, str> {
2664     fn from_iter<I: IntoIterator<Item = char>>(it: I) -> Cow<'a, str> {
2665         Cow::Owned(FromIterator::from_iter(it))
2666     }
2667 }
2668
2669 #[cfg(not(no_global_oom_handling))]
2670 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2671 impl<'a, 'b> FromIterator<&'b str> for Cow<'a, str> {
2672     fn from_iter<I: IntoIterator<Item = &'b str>>(it: I) -> Cow<'a, str> {
2673         Cow::Owned(FromIterator::from_iter(it))
2674     }
2675 }
2676
2677 #[cfg(not(no_global_oom_handling))]
2678 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2679 impl<'a> FromIterator<String> for Cow<'a, str> {
2680     fn from_iter<I: IntoIterator<Item = String>>(it: I) -> Cow<'a, str> {
2681         Cow::Owned(FromIterator::from_iter(it))
2682     }
2683 }
2684
2685 #[stable(feature = "from_string_for_vec_u8", since = "1.14.0")]
2686 impl From<String> for Vec<u8> {
2687     /// Converts the given [`String`] to a vector [`Vec`] that holds values of type [`u8`].
2688     ///
2689     /// # Examples
2690     ///
2691     /// Basic usage:
2692     ///
2693     /// ```
2694     /// let s1 = String::from("hello world");
2695     /// let v1 = Vec::from(s1);
2696     ///
2697     /// for b in v1 {
2698     ///     println!("{}", b);
2699     /// }
2700     /// ```
2701     fn from(string: String) -> Vec<u8> {
2702         string.into_bytes()
2703     }
2704 }
2705
2706 #[cfg(not(no_global_oom_handling))]
2707 #[stable(feature = "rust1", since = "1.0.0")]
2708 impl fmt::Write for String {
2709     #[inline]
2710     fn write_str(&mut self, s: &str) -> fmt::Result {
2711         self.push_str(s);
2712         Ok(())
2713     }
2714
2715     #[inline]
2716     fn write_char(&mut self, c: char) -> fmt::Result {
2717         self.push(c);
2718         Ok(())
2719     }
2720 }
2721
2722 /// A draining iterator for `String`.
2723 ///
2724 /// This struct is created by the [`drain`] method on [`String`]. See its
2725 /// documentation for more.
2726 ///
2727 /// [`drain`]: String::drain
2728 #[stable(feature = "drain", since = "1.6.0")]
2729 pub struct Drain<'a> {
2730     /// Will be used as &'a mut String in the destructor
2731     string: *mut String,
2732     /// Start of part to remove
2733     start: usize,
2734     /// End of part to remove
2735     end: usize,
2736     /// Current remaining range to remove
2737     iter: Chars<'a>,
2738 }
2739
2740 #[stable(feature = "collection_debug", since = "1.17.0")]
2741 impl fmt::Debug for Drain<'_> {
2742     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2743         f.debug_tuple("Drain").field(&self.as_str()).finish()
2744     }
2745 }
2746
2747 #[stable(feature = "drain", since = "1.6.0")]
2748 unsafe impl Sync for Drain<'_> {}
2749 #[stable(feature = "drain", since = "1.6.0")]
2750 unsafe impl Send for Drain<'_> {}
2751
2752 #[stable(feature = "drain", since = "1.6.0")]
2753 impl Drop for Drain<'_> {
2754     fn drop(&mut self) {
2755         unsafe {
2756             // Use Vec::drain. "Reaffirm" the bounds checks to avoid
2757             // panic code being inserted again.
2758             let self_vec = (*self.string).as_mut_vec();
2759             if self.start <= self.end && self.end <= self_vec.len() {
2760                 self_vec.drain(self.start..self.end);
2761             }
2762         }
2763     }
2764 }
2765
2766 impl<'a> Drain<'a> {
2767     /// Returns the remaining (sub)string of this iterator as a slice.
2768     ///
2769     /// # Examples
2770     ///
2771     /// ```
2772     /// #![feature(string_drain_as_str)]
2773     /// let mut s = String::from("abc");
2774     /// let mut drain = s.drain(..);
2775     /// assert_eq!(drain.as_str(), "abc");
2776     /// let _ = drain.next().unwrap();
2777     /// assert_eq!(drain.as_str(), "bc");
2778     /// ```
2779     #[unstable(feature = "string_drain_as_str", issue = "76905")] // Note: uncomment AsRef impls below when stabilizing.
2780     pub fn as_str(&self) -> &str {
2781         self.iter.as_str()
2782     }
2783 }
2784
2785 // Uncomment when stabilizing `string_drain_as_str`.
2786 // #[unstable(feature = "string_drain_as_str", issue = "76905")]
2787 // impl<'a> AsRef<str> for Drain<'a> {
2788 //     fn as_ref(&self) -> &str {
2789 //         self.as_str()
2790 //     }
2791 // }
2792 //
2793 // #[unstable(feature = "string_drain_as_str", issue = "76905")]
2794 // impl<'a> AsRef<[u8]> for Drain<'a> {
2795 //     fn as_ref(&self) -> &[u8] {
2796 //         self.as_str().as_bytes()
2797 //     }
2798 // }
2799
2800 #[stable(feature = "drain", since = "1.6.0")]
2801 impl Iterator for Drain<'_> {
2802     type Item = char;
2803
2804     #[inline]
2805     fn next(&mut self) -> Option<char> {
2806         self.iter.next()
2807     }
2808
2809     fn size_hint(&self) -> (usize, Option<usize>) {
2810         self.iter.size_hint()
2811     }
2812
2813     #[inline]
2814     fn last(mut self) -> Option<char> {
2815         self.next_back()
2816     }
2817 }
2818
2819 #[stable(feature = "drain", since = "1.6.0")]
2820 impl DoubleEndedIterator for Drain<'_> {
2821     #[inline]
2822     fn next_back(&mut self) -> Option<char> {
2823         self.iter.next_back()
2824     }
2825 }
2826
2827 #[stable(feature = "fused", since = "1.26.0")]
2828 impl FusedIterator for Drain<'_> {}
2829
2830 #[cfg(not(no_global_oom_handling))]
2831 #[stable(feature = "from_char_for_string", since = "1.46.0")]
2832 impl From<char> for String {
2833     /// Allocates an owned [`String`] from a single character.
2834     ///
2835     /// # Example
2836     /// ```rust
2837     /// let c: char = 'a';
2838     /// let s: String = String::from(c);
2839     /// assert_eq!("a", &s[..]);
2840     /// ```
2841     #[inline]
2842     fn from(c: char) -> Self {
2843         c.to_string()
2844     }
2845 }