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