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