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