Skip to main content

alloc/
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))]
46use core::ascii;
47use core::error::Error;
48use core::iter::FusedIterator;
49#[cfg(not(no_global_oom_handling))]
50use core::iter::from_fn;
51#[cfg(not(no_global_oom_handling))]
52use core::mem::MaybeUninit;
53#[cfg(not(no_global_oom_handling))]
54use core::num::Saturating;
55#[cfg(not(no_global_oom_handling))]
56use core::ops::Add;
57#[cfg(not(no_global_oom_handling))]
58use core::ops::AddAssign;
59use core::ops::{self, Range, RangeBounds};
60use core::str::pattern::{Pattern, Utf8Pattern};
61use core::{fmt, hash, hint, ptr, slice};
62
63#[cfg(not(no_global_oom_handling))]
64use crate::alloc::Allocator;
65#[cfg(not(no_global_oom_handling))]
66use crate::borrow::{Cow, ToOwned};
67use crate::boxed::Box;
68use crate::collections::TryReserveError;
69use crate::str::{self, CharIndices, Chars, Utf8Error, from_utf8_unchecked_mut};
70#[cfg(not(no_global_oom_handling))]
71use crate::str::{FromStr, from_boxed_utf8_unchecked};
72use crate::vec::{self, Vec};
73
74/// A UTF-8–encoded, growable string.
75///
76/// `String` is the most common string type. It has ownership over the contents
77/// of the string, stored in a heap-allocated buffer (see [Representation](#representation)).
78/// It is closely related to its borrowed 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 `char`s:
124///
125/// ```
126/// // `s` is ASCII which represents each `char` as one byte
127/// let s = "hello";
128/// assert_eq!(s.len(), 5);
129///
130/// // A `char` array with the same contents would be longer because
131/// // every `char` is four bytes
132/// let s = ['h', 'e', 'l', 'l', 'o'];
133/// let size: usize = s.into_iter().map(|c| size_of_val(&c)).sum();
134/// assert_eq!(size, 20);
135///
136/// // However, for non-ASCII strings, the difference will be smaller
137/// // and sometimes they are the same
138/// let s = "πŸ’–πŸ’–πŸ’–πŸ’–πŸ’–";
139/// assert_eq!(s.len(), 20);
140///
141/// let s = ['πŸ’–', 'πŸ’–', 'πŸ’–', 'πŸ’–', 'πŸ’–'];
142/// let size: usize = s.into_iter().map(|c| size_of_val(&c)).sum();
143/// assert_eq!(size, 20);
144/// ```
145///
146/// This raises interesting questions as to how `s[i]` should work.
147/// What should `i` be here? Several options include byte indices and
148/// `char` indices but, because of UTF-8 encoding, only byte indices
149/// would provide constant time indexing. Getting the `i`th `char`, for
150/// example, is available using [`chars`]:
151///
152/// ```
153/// let s = "hello";
154/// let third_character = s.chars().nth(2);
155/// assert_eq!(third_character, Some('l'));
156///
157/// let s = "πŸ’–πŸ’–πŸ’–πŸ’–πŸ’–";
158/// let third_character = s.chars().nth(2);
159/// assert_eq!(third_character, Some('πŸ’–'));
160/// ```
161///
162/// Next, what should `s[i]` return? Because indexing returns a reference
163/// to underlying data it could be `&u8`, `&[u8]`, or something similar.
164/// Since we're only providing one index, `&u8` makes the most sense but that
165/// might not be what the user expects and can be explicitly achieved with
166/// [`as_bytes()`]:
167///
168/// ```
169/// // The first byte is 104 - the byte value of `'h'`
170/// let s = "hello";
171/// assert_eq!(s.as_bytes()[0], 104);
172/// // or
173/// assert_eq!(s.as_bytes()[0], b'h');
174///
175/// // The first byte is 240 which isn't obviously useful
176/// let s = "πŸ’–πŸ’–πŸ’–πŸ’–πŸ’–";
177/// assert_eq!(s.as_bytes()[0], 240);
178/// ```
179///
180/// Due to these ambiguities/restrictions, indexing with a `usize` is simply
181/// forbidden:
182///
183/// ```compile_fail,E0277
184/// let s = "hello";
185///
186/// // The following will not compile!
187/// println!("The first letter of s is {}", s[0]);
188/// ```
189///
190/// It is more clear, however, how `&s[i..j]` should work (that is,
191/// indexing with a range). It should accept byte indices (to be constant-time)
192/// and return a `&str` which is UTF-8 encoded. This is also called "string slicing".
193/// Note this will panic if the byte indices provided are not character
194/// boundaries - see [`is_char_boundary`] for more details. See the implementations
195/// for [`SliceIndex<str>`] for more details on string slicing. For a non-panicking
196/// version of string slicing, see [`get`].
197///
198/// [`OsString`]: ../../std/ffi/struct.OsString.html "ffi::OsString"
199/// [`SliceIndex<str>`]: core::slice::SliceIndex
200/// [`as_bytes()`]: str::as_bytes
201/// [`get`]: str::get
202/// [`is_char_boundary`]: str::is_char_boundary
203///
204/// The [`bytes`] and [`chars`] methods return iterators over the bytes and
205/// codepoints of the string, respectively. To iterate over codepoints along
206/// with byte indices, use [`char_indices`].
207///
208/// [`bytes`]: str::bytes
209/// [`chars`]: str::chars
210/// [`char_indices`]: str::char_indices
211///
212/// # Deref
213///
214/// `String` implements <code>[Deref]<Target = [str]></code>, and so inherits all of [`str`]'s
215/// methods. In addition, this means that you can pass a `String` to a
216/// function which takes a [`&str`] by using an ampersand (`&`):
217///
218/// ```
219/// fn takes_str(s: &str) { }
220///
221/// let s = String::from("Hello");
222///
223/// takes_str(&s);
224/// ```
225///
226/// This will create a [`&str`] from the `String` and pass it in. This
227/// conversion is very inexpensive, and so generally, functions will accept
228/// [`&str`]s as arguments unless they need a `String` for some specific
229/// reason.
230///
231/// In certain cases Rust doesn't have enough information to make this
232/// conversion, known as [`Deref`] coercion. In the following example a string
233/// slice [`&'a str`][`&str`] implements the trait `TraitExample`, and the function
234/// `example_func` takes anything that implements the trait. In this case Rust
235/// would need to make two implicit conversions, which Rust doesn't have the
236/// means to do. For that reason, the following example will not compile.
237///
238/// ```compile_fail,E0277
239/// trait TraitExample {}
240///
241/// impl<'a> TraitExample for &'a str {}
242///
243/// fn example_func<A: TraitExample>(example_arg: A) {}
244///
245/// let example_string = String::from("example_string");
246/// example_func(&example_string);
247/// ```
248///
249/// There are two options that would work instead. The first would be to
250/// change the line `example_func(&example_string);` to
251/// `example_func(example_string.as_str());`, using the method [`as_str()`]
252/// to explicitly extract the string slice containing the string. The second
253/// way changes `example_func(&example_string);` to
254/// `example_func(&*example_string);`. In this case we are dereferencing a
255/// `String` to a [`str`], then referencing the [`str`] back to
256/// [`&str`]. The second way is more idiomatic, however both work to do the
257/// conversion explicitly rather than relying on the implicit conversion.
258///
259/// # Representation
260///
261/// A `String` is made up of three components: a pointer to some bytes, a
262/// length, and a capacity. The pointer points to the internal buffer which `String`
263/// uses to store its data. The length is the number of bytes currently stored
264/// in the buffer, and the capacity is the size of the buffer in bytes. As such,
265/// the length will always be less than or equal to the capacity.
266///
267/// This buffer is always stored on the heap.
268///
269/// You can look at these with the [`as_ptr`], [`len`], and [`capacity`]
270/// methods:
271///
272/// ```
273/// let story = String::from("Once upon a time...");
274///
275/// // Deconstruct the String into parts.
276/// let (ptr, len, capacity) = story.into_raw_parts();
277///
278/// // story has nineteen bytes
279/// assert_eq!(19, len);
280///
281/// // We can re-build a String out of ptr, len, and capacity. This is all
282/// // unsafe because we are responsible for making sure the components are
283/// // valid:
284/// let s = unsafe { String::from_raw_parts(ptr, len, capacity) } ;
285///
286/// assert_eq!(String::from("Once upon a time..."), s);
287/// ```
288///
289/// [`as_ptr`]: str::as_ptr
290/// [`len`]: String::len
291/// [`capacity`]: String::capacity
292///
293/// If a `String` has enough capacity, adding elements to it will not
294/// re-allocate. For example, consider this program:
295///
296/// ```
297/// let mut s = String::new();
298///
299/// println!("{}", s.capacity());
300///
301/// for _ in 0..5 {
302///     s.push_str("hello");
303///     println!("{}", s.capacity());
304/// }
305/// ```
306///
307/// This will output the following:
308///
309/// ```text
310/// 0
311/// 8
312/// 16
313/// 16
314/// 32
315/// 32
316/// ```
317///
318/// At first, we have no memory allocated at all, but as we append to the
319/// string, it increases its capacity appropriately. If we instead use the
320/// [`with_capacity`] method to allocate the correct capacity initially:
321///
322/// ```
323/// let mut s = String::with_capacity(25);
324///
325/// println!("{}", s.capacity());
326///
327/// for _ in 0..5 {
328///     s.push_str("hello");
329///     println!("{}", s.capacity());
330/// }
331/// ```
332///
333/// [`with_capacity`]: String::with_capacity
334///
335/// We end up with a different output:
336///
337/// ```text
338/// 25
339/// 25
340/// 25
341/// 25
342/// 25
343/// 25
344/// ```
345///
346/// Here, there's no need to allocate more memory inside the loop.
347///
348/// [str]: prim@str "str"
349/// [`str`]: prim@str "str"
350/// [`&str`]: prim@str "&str"
351/// [Deref]: core::ops::Deref "ops::Deref"
352/// [`Deref`]: core::ops::Deref "ops::Deref"
353/// [`as_str()`]: String::as_str
354#[derive(PartialEq, PartialOrd, Eq, Ord)]
355#[stable(feature = "rust1", since = "1.0.0")]
356#[lang = "String"]
357pub struct String {
358    vec: Vec<u8>,
359}
360
361/// A possible error value when converting a `String` from a UTF-8 byte vector.
362///
363/// This type is the error type for the [`from_utf8`] method on [`String`]. It
364/// is designed in such a way to carefully avoid reallocations: the
365/// [`into_bytes`] method will give back the byte vector that was used in the
366/// conversion attempt.
367///
368/// [`from_utf8`]: String::from_utf8
369/// [`into_bytes`]: FromUtf8Error::into_bytes
370///
371/// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
372/// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
373/// an analogue to `FromUtf8Error`, and you can get one from a `FromUtf8Error`
374/// through the [`utf8_error`] method.
375///
376/// [`Utf8Error`]: str::Utf8Error "std::str::Utf8Error"
377/// [`std::str`]: core::str "std::str"
378/// [`&str`]: prim@str "&str"
379/// [`utf8_error`]: FromUtf8Error::utf8_error
380///
381/// # Examples
382///
383/// ```
384/// // some invalid bytes, in a vector
385/// let bytes = vec![0, 159];
386///
387/// let value = String::from_utf8(bytes);
388///
389/// assert!(value.is_err());
390/// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
391/// ```
392#[stable(feature = "rust1", since = "1.0.0")]
393#[cfg_attr(not(no_global_oom_handling), derive(Clone))]
394#[derive(Debug, PartialEq, Eq)]
395pub struct FromUtf8Error {
396    bytes: Vec<u8>,
397    error: Utf8Error,
398}
399
400/// A possible error value when converting a `String` from a UTF-16 byte slice.
401///
402/// This type is the error type for the [`from_utf16`] method on [`String`].
403///
404/// [`from_utf16`]: String::from_utf16
405///
406/// # Examples
407///
408/// ```
409/// // π„žmu<invalid>ic
410/// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
411///           0xD800, 0x0069, 0x0063];
412///
413/// assert!(String::from_utf16(v).is_err());
414/// ```
415#[stable(feature = "rust1", since = "1.0.0")]
416#[derive(Debug)]
417pub struct FromUtf16Error {
418    kind: FromUtf16ErrorKind,
419}
420
421#[cfg_attr(no_global_oom_handling, expect(dead_code))]
422#[derive(Clone, PartialEq, Eq, Debug)]
423enum FromUtf16ErrorKind {
424    LoneSurrogate,
425    OddBytes,
426}
427
428impl String {
429    /// Creates a new empty `String`.
430    ///
431    /// Given that the `String` is empty, this will not allocate any initial
432    /// buffer. While that means that this initial operation is very
433    /// inexpensive, it may cause excessive allocation later when you add
434    /// data. If you have an idea of how much data the `String` will hold,
435    /// consider the [`with_capacity`] method to prevent excessive
436    /// re-allocation.
437    ///
438    /// [`with_capacity`]: String::with_capacity
439    ///
440    /// # Examples
441    ///
442    /// ```
443    /// let s = String::new();
444    /// ```
445    #[inline]
446    #[rustc_const_stable(feature = "const_string_new", since = "1.39.0")]
447    #[rustc_diagnostic_item = "string_new"]
448    #[stable(feature = "rust1", since = "1.0.0")]
449    #[must_use]
450    pub const fn new() -> String {
451        String { vec: Vec::new() }
452    }
453
454    /// Creates a new empty `String` with at least the specified capacity.
455    ///
456    /// `String`s have an internal buffer to hold their data. The capacity is
457    /// the length of that buffer, and can be queried with the [`capacity`]
458    /// method. This method creates an empty `String`, but one with an initial
459    /// buffer that can hold at least `capacity` bytes. This is useful when you
460    /// may be appending a bunch of data to the `String`, reducing the number of
461    /// reallocations it needs to do.
462    ///
463    /// [`capacity`]: String::capacity
464    ///
465    /// If the given capacity is `0`, no allocation will occur, and this method
466    /// is identical to the [`new`] method.
467    ///
468    /// [`new`]: String::new
469    ///
470    /// # Panics
471    ///
472    /// Panics if the capacity exceeds `isize::MAX` _bytes_.
473    ///
474    /// # Examples
475    ///
476    /// ```
477    /// let mut s = String::with_capacity(10);
478    ///
479    /// // The String contains no chars, even though it has capacity for more
480    /// assert_eq!(s.len(), 0);
481    ///
482    /// // These are all done without reallocating...
483    /// let cap = s.capacity();
484    /// for _ in 0..10 {
485    ///     s.push('a');
486    /// }
487    ///
488    /// assert_eq!(s.capacity(), cap);
489    ///
490    /// // ...but this may make the string reallocate
491    /// s.push('a');
492    /// ```
493    #[cfg(not(no_global_oom_handling))]
494    #[inline]
495    #[stable(feature = "rust1", since = "1.0.0")]
496    #[must_use]
497    pub fn with_capacity(capacity: usize) -> String {
498        String { vec: Vec::with_capacity(capacity) }
499    }
500
501    /// Creates a new empty `String` with at least the specified capacity.
502    ///
503    /// # Errors
504    ///
505    /// Returns [`Err`] if the capacity exceeds `isize::MAX` bytes,
506    /// or if the memory allocator reports failure.
507    ///
508    #[inline]
509    #[unstable(feature = "try_with_capacity", issue = "91913")]
510    pub fn try_with_capacity(capacity: usize) -> Result<String, TryReserveError> {
511        Ok(String { vec: Vec::try_with_capacity(capacity)? })
512    }
513
514    /// Converts a vector of bytes to a `String`.
515    ///
516    /// A string ([`String`]) is made of bytes ([`u8`]), and a vector of bytes
517    /// ([`Vec<u8>`]) is made of bytes, so this function converts between the
518    /// two. Not all byte slices are valid `String`s, however: `String`
519    /// requires that it is valid UTF-8. `from_utf8()` checks to ensure that
520    /// the bytes are valid UTF-8, and then does the conversion.
521    ///
522    /// If you are sure that the byte slice is valid UTF-8, and you don't want
523    /// to incur the overhead of the validity check, there is an unsafe version
524    /// of this function, [`from_utf8_unchecked`], which has the same behavior
525    /// but skips the check.
526    ///
527    /// This method will take care to not copy the vector, for efficiency's
528    /// sake.
529    ///
530    /// If you need a [`&str`] instead of a `String`, consider
531    /// [`str::from_utf8`].
532    ///
533    /// The inverse of this method is [`into_bytes`].
534    ///
535    /// # Errors
536    ///
537    /// Returns [`Err`] if the slice is not UTF-8 with a description as to why the
538    /// provided bytes are not UTF-8. The vector you moved in is also included.
539    ///
540    /// # Examples
541    ///
542    /// Basic usage:
543    ///
544    /// ```
545    /// // some bytes, in a vector
546    /// let sparkle_heart = vec![240, 159, 146, 150];
547    ///
548    /// // We know these bytes are valid, so we'll use `unwrap()`.
549    /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
550    ///
551    /// assert_eq!("πŸ’–", sparkle_heart);
552    /// ```
553    ///
554    /// Incorrect bytes:
555    ///
556    /// ```
557    /// // some invalid bytes, in a vector
558    /// let sparkle_heart = vec![0, 159, 146, 150];
559    ///
560    /// assert!(String::from_utf8(sparkle_heart).is_err());
561    /// ```
562    ///
563    /// See the docs for [`FromUtf8Error`] for more details on what you can do
564    /// with this error.
565    ///
566    /// [`from_utf8_unchecked`]: String::from_utf8_unchecked
567    /// [`Vec<u8>`]: crate::vec::Vec "Vec"
568    /// [`&str`]: prim@str "&str"
569    /// [`into_bytes`]: String::into_bytes
570    #[inline]
571    #[stable(feature = "rust1", since = "1.0.0")]
572    #[rustc_diagnostic_item = "string_from_utf8"]
573    pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error> {
574        match str::from_utf8(&vec) {
575            Ok(..) => Ok(String { vec }),
576            Err(e) => Err(FromUtf8Error { bytes: vec, error: e }),
577        }
578    }
579
580    /// Converts a slice of bytes to a string, including invalid characters.
581    ///
582    /// Strings are made of bytes ([`u8`]), and a slice of bytes
583    /// ([`&[u8]`][byteslice]) is made of bytes, so this function converts
584    /// between the two. Not all byte slices are valid strings, however: strings
585    /// are required to be valid UTF-8. During this conversion,
586    /// `from_utf8_lossy()` will replace any invalid UTF-8 sequences with
587    /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD], which looks like this: οΏ½
588    ///
589    /// [byteslice]: prim@slice
590    /// [U+FFFD]: char::REPLACEMENT_CHARACTER
591    ///
592    /// If you are sure that the byte slice is valid UTF-8, and you don't want
593    /// to incur the overhead of the conversion, there is an unsafe version
594    /// of this function, [`from_utf8_unchecked`], which has the same behavior
595    /// but skips the checks.
596    ///
597    /// [`from_utf8_unchecked`]: String::from_utf8_unchecked
598    ///
599    /// This function returns a [`Cow<'a, str>`]. If our byte slice is invalid
600    /// UTF-8, then we need to insert the replacement characters, which will
601    /// change the size of the string, and hence, require a `String`. But if
602    /// it's already valid UTF-8, we don't need a new allocation. This return
603    /// type allows us to handle both cases.
604    ///
605    /// [`Cow<'a, str>`]: crate::borrow::Cow "borrow::Cow"
606    ///
607    /// # Examples
608    ///
609    /// Basic usage:
610    ///
611    /// ```
612    /// // some bytes, in a vector
613    /// let sparkle_heart = vec![240, 159, 146, 150];
614    ///
615    /// let sparkle_heart = String::from_utf8_lossy(&sparkle_heart);
616    ///
617    /// assert_eq!("πŸ’–", sparkle_heart);
618    /// ```
619    ///
620    /// Incorrect bytes:
621    ///
622    /// ```
623    /// // some invalid bytes
624    /// let input = b"Hello \xF0\x90\x80World";
625    /// let output = String::from_utf8_lossy(input);
626    ///
627    /// assert_eq!("Hello οΏ½World", output);
628    /// ```
629    #[must_use]
630    #[cfg(not(no_global_oom_handling))]
631    #[stable(feature = "rust1", since = "1.0.0")]
632    pub fn from_utf8_lossy(v: &[u8]) -> Cow<'_, str> {
633        let mut iter = v.utf8_chunks();
634
635        let Some(chunk) = iter.next() else {
636            return Cow::Borrowed("");
637        };
638        let first_valid = chunk.valid();
639        if chunk.invalid().is_empty() {
640            debug_assert_eq!(first_valid.len(), v.len());
641            return Cow::Borrowed(first_valid);
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 chunk in iter {
651            res.push_str(chunk.valid());
652            if !chunk.invalid().is_empty() {
653                res.push_str(REPLACEMENT);
654            }
655        }
656
657        Cow::Owned(res)
658    }
659
660    /// Converts a [`Vec<u8>`] to a `String`, substituting invalid UTF-8
661    /// sequences with replacement characters.
662    ///
663    /// See [`from_utf8_lossy`] for more details.
664    ///
665    /// [`from_utf8_lossy`]: String::from_utf8_lossy
666    ///
667    /// Note that this function does not guarantee reuse of the original `Vec`
668    /// allocation.
669    ///
670    /// # Examples
671    ///
672    /// Basic usage:
673    ///
674    /// ```
675    /// // some bytes, in a vector
676    /// let sparkle_heart = vec![240, 159, 146, 150];
677    ///
678    /// let sparkle_heart = String::from_utf8_lossy_owned(sparkle_heart);
679    ///
680    /// assert_eq!(String::from("πŸ’–"), sparkle_heart);
681    /// ```
682    ///
683    /// Incorrect bytes:
684    ///
685    /// ```
686    /// // some invalid bytes
687    /// let input: Vec<u8> = b"Hello \xF0\x90\x80World".into();
688    /// let output = String::from_utf8_lossy_owned(input);
689    ///
690    /// assert_eq!(String::from("Hello οΏ½World"), output);
691    /// ```
692    #[must_use]
693    #[cfg(not(no_global_oom_handling))]
694    #[stable(feature = "string_from_utf8_lossy_owned", since = "1.99.0")]
695    pub fn from_utf8_lossy_owned(v: Vec<u8>) -> String {
696        if let Cow::Owned(string) = String::from_utf8_lossy(&v) {
697            string
698        } else {
699            // SAFETY: `String::from_utf8_lossy`'s contract ensures that if
700            // it returns a `Cow::Borrowed`, it is a valid UTF-8 string.
701            // Otherwise, it returns a new allocation of an owned `String`, with
702            // replacement characters for invalid sequences, which is returned
703            // above.
704            unsafe { String::from_utf8_unchecked(v) }
705        }
706    }
707
708    /// Decode a native endian UTF-16–encoded vector `v` into a `String`,
709    /// returning [`Err`] if `v` contains any invalid data.
710    ///
711    /// # Examples
712    ///
713    /// ```
714    /// // π„žmusic
715    /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
716    ///           0x0073, 0x0069, 0x0063];
717    /// assert_eq!(String::from("π„žmusic"),
718    ///            String::from_utf16(v).unwrap());
719    ///
720    /// // π„žmu<invalid>ic
721    /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
722    ///           0xD800, 0x0069, 0x0063];
723    /// assert!(String::from_utf16(v).is_err());
724    /// ```
725    #[cfg(not(no_global_oom_handling))]
726    #[stable(feature = "rust1", since = "1.0.0")]
727    pub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error> {
728        Self::from_utf16_units(v.iter().cloned(), v.len())
729    }
730
731    /// Decodes an iterator of UTF-16 code units into a `String`, returning
732    /// [`Err`] on the first lone surrogate. `capacity` should be the number of
733    /// code units, which is used to preallocate the output buffer.
734    // This isn't done via collect::<Result<_, _>>() for performance reasons.
735    // FIXME: the function can be simplified again when #48994 is closed.
736    #[cfg(not(no_global_oom_handling))]
737    #[inline]
738    fn from_utf16_units(
739        units: impl Iterator<Item = u16>,
740        capacity: usize,
741    ) -> Result<String, FromUtf16Error> {
742        let mut ret = String::with_capacity(capacity);
743        for c in char::decode_utf16(units) {
744            let Ok(c) = c else {
745                return Err(FromUtf16Error { kind: FromUtf16ErrorKind::LoneSurrogate });
746            };
747            ret.push(c);
748        }
749        Ok(ret)
750    }
751
752    /// Decode a native endian UTF-16–encoded slice `v` into a `String`,
753    /// replacing invalid data with [the replacement character (`U+FFFD`)][U+FFFD].
754    ///
755    /// Unlike [`from_utf8_lossy`] which returns a [`Cow<'a, str>`],
756    /// `from_utf16_lossy` returns a `String` since the UTF-16 to UTF-8
757    /// conversion requires a memory allocation.
758    ///
759    /// [`from_utf8_lossy`]: String::from_utf8_lossy
760    /// [`Cow<'a, str>`]: crate::borrow::Cow "borrow::Cow"
761    /// [U+FFFD]: char::REPLACEMENT_CHARACTER
762    ///
763    /// # Examples
764    ///
765    /// ```
766    /// // π„žmus<invalid>ic<invalid>
767    /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
768    ///           0x0073, 0xDD1E, 0x0069, 0x0063,
769    ///           0xD834];
770    ///
771    /// assert_eq!(String::from("π„žmus\u{FFFD}ic\u{FFFD}"),
772    ///            String::from_utf16_lossy(v));
773    /// ```
774    #[cfg(not(no_global_oom_handling))]
775    #[must_use]
776    #[inline]
777    #[stable(feature = "rust1", since = "1.0.0")]
778    pub fn from_utf16_lossy(v: &[u16]) -> String {
779        char::decode_utf16(v.iter().cloned())
780            .map(|r| r.unwrap_or(char::REPLACEMENT_CHARACTER))
781            .collect()
782    }
783
784    /// Decode a UTF-16LE–encoded vector `v` into a `String`,
785    /// returning [`Err`] if `v` contains any invalid data.
786    ///
787    /// # Examples
788    ///
789    /// Basic usage:
790    ///
791    /// ```
792    /// // π„žmusic
793    /// let v = &[0x34, 0xD8, 0x1E, 0xDD, 0x6d, 0x00, 0x75, 0x00,
794    ///           0x73, 0x00, 0x69, 0x00, 0x63, 0x00];
795    /// assert_eq!(String::from("π„žmusic"),
796    ///            String::from_utf16le(v).unwrap());
797    ///
798    /// // π„žmu<invalid>ic
799    /// let v = &[0x34, 0xD8, 0x1E, 0xDD, 0x6d, 0x00, 0x75, 0x00,
800    ///           0x00, 0xD8, 0x69, 0x00, 0x63, 0x00];
801    /// assert!(String::from_utf16le(v).is_err());
802    /// ```
803    #[cfg(not(no_global_oom_handling))]
804    #[stable(feature = "str_from_utf16_endian", since = "1.98.0")]
805    pub fn from_utf16le(v: &[u8]) -> Result<String, FromUtf16Error> {
806        let (chunks, []) = v.as_chunks::<2>() else {
807            return Err(FromUtf16Error { kind: FromUtf16ErrorKind::OddBytes });
808        };
809        // SAFETY: The aligned part of `v` can be transmuted into a valid u16 slice.
810        match (cfg!(target_endian = "little"), unsafe { v.align_to::<u16>() }) {
811            (true, ([], v, [])) => Self::from_utf16(v),
812            _ => {
813                Self::from_utf16_units(chunks.iter().copied().map(u16::from_le_bytes), chunks.len())
814            }
815        }
816    }
817
818    /// Decode a UTF-16LE–encoded slice `v` into a `String`, replacing
819    /// invalid data with [the replacement character (`U+FFFD`)][U+FFFD].
820    ///
821    /// Unlike [`from_utf8_lossy`] which returns a [`Cow<'a, str>`],
822    /// `from_utf16le_lossy` returns a `String` since the UTF-16 to UTF-8
823    /// conversion requires a memory allocation.
824    ///
825    /// [`from_utf8_lossy`]: String::from_utf8_lossy
826    /// [`Cow<'a, str>`]: crate::borrow::Cow "borrow::Cow"
827    /// [U+FFFD]: char::REPLACEMENT_CHARACTER
828    ///
829    /// # Examples
830    ///
831    /// Basic usage:
832    ///
833    /// ```
834    /// // π„žmus<invalid>ic<invalid>
835    /// let v = &[0x34, 0xD8, 0x1E, 0xDD, 0x6d, 0x00, 0x75, 0x00,
836    ///           0x73, 0x00, 0x1E, 0xDD, 0x69, 0x00, 0x63, 0x00,
837    ///           0x34, 0xD8];
838    ///
839    /// assert_eq!(String::from("π„žmus\u{FFFD}ic\u{FFFD}"),
840    ///            String::from_utf16le_lossy(v));
841    /// ```
842    #[cfg(not(no_global_oom_handling))]
843    #[stable(feature = "str_from_utf16_endian", since = "1.98.0")]
844    pub fn from_utf16le_lossy(v: &[u8]) -> String {
845        // SAFETY: The aligned part of `v` can be transmuted into a valid u16 slice.
846        match (cfg!(target_endian = "little"), unsafe { v.align_to::<u16>() }) {
847            (true, ([], v, [])) => Self::from_utf16_lossy(v),
848            (true, ([], v, [_remainder])) => Self::from_utf16_lossy(v) + "\u{FFFD}",
849            _ => {
850                let (chunks, remainder) = v.as_chunks::<2>();
851                let string = char::decode_utf16(chunks.iter().copied().map(u16::from_le_bytes))
852                    .map(|r| r.unwrap_or(char::REPLACEMENT_CHARACTER))
853                    .collect();
854                if remainder.is_empty() { string } else { string + "\u{FFFD}" }
855            }
856        }
857    }
858
859    /// Decode a UTF-16BE–encoded vector `v` into a `String`,
860    /// returning [`Err`] if `v` contains any invalid data.
861    ///
862    /// # Examples
863    ///
864    /// Basic usage:
865    ///
866    /// ```
867    /// // π„žmusic
868    /// let v = &[0xD8, 0x34, 0xDD, 0x1E, 0x00, 0x6d, 0x00, 0x75,
869    ///           0x00, 0x73, 0x00, 0x69, 0x00, 0x63];
870    /// assert_eq!(String::from("π„žmusic"),
871    ///            String::from_utf16be(v).unwrap());
872    ///
873    /// // π„žmu<invalid>ic
874    /// let v = &[0xD8, 0x34, 0xDD, 0x1E, 0x00, 0x6d, 0x00, 0x75,
875    ///           0xD8, 0x00, 0x00, 0x69, 0x00, 0x63];
876    /// assert!(String::from_utf16be(v).is_err());
877    /// ```
878    #[cfg(not(no_global_oom_handling))]
879    #[stable(feature = "str_from_utf16_endian", since = "1.98.0")]
880    pub fn from_utf16be(v: &[u8]) -> Result<String, FromUtf16Error> {
881        let (chunks, []) = v.as_chunks::<2>() else {
882            return Err(FromUtf16Error { kind: FromUtf16ErrorKind::OddBytes });
883        };
884        // SAFETY: The aligned part of `v` can be transmuted into a valid u16 slice.
885        match (cfg!(target_endian = "big"), unsafe { v.align_to::<u16>() }) {
886            (true, ([], v, [])) => Self::from_utf16(v),
887            _ => {
888                Self::from_utf16_units(chunks.iter().copied().map(u16::from_be_bytes), chunks.len())
889            }
890        }
891    }
892
893    /// Decode a UTF-16BE–encoded slice `v` into a `String`, replacing
894    /// invalid data with [the replacement character (`U+FFFD`)][U+FFFD].
895    ///
896    /// Unlike [`from_utf8_lossy`] which returns a [`Cow<'a, str>`],
897    /// `from_utf16le_lossy` returns a `String` since the UTF-16 to UTF-8
898    /// conversion requires a memory allocation.
899    ///
900    /// [`from_utf8_lossy`]: String::from_utf8_lossy
901    /// [`Cow<'a, str>`]: crate::borrow::Cow "borrow::Cow"
902    /// [U+FFFD]: char::REPLACEMENT_CHARACTER
903    ///
904    /// # Examples
905    ///
906    /// Basic usage:
907    ///
908    /// ```
909    /// // π„žmus<invalid>ic<invalid>
910    /// let v = &[0xD8, 0x34, 0xDD, 0x1E, 0x00, 0x6d, 0x00, 0x75,
911    ///           0x00, 0x73, 0xDD, 0x1E, 0x00, 0x69, 0x00, 0x63,
912    ///           0xD8, 0x34];
913    ///
914    /// assert_eq!(String::from("π„žmus\u{FFFD}ic\u{FFFD}"),
915    ///            String::from_utf16be_lossy(v));
916    /// ```
917    #[cfg(not(no_global_oom_handling))]
918    #[stable(feature = "str_from_utf16_endian", since = "1.98.0")]
919    pub fn from_utf16be_lossy(v: &[u8]) -> String {
920        // SAFETY: The aligned part of `v` can be transmuted into a valid u16 slice.
921        match (cfg!(target_endian = "big"), unsafe { v.align_to::<u16>() }) {
922            (true, ([], v, [])) => Self::from_utf16_lossy(v),
923            (true, ([], v, [_remainder])) => Self::from_utf16_lossy(v) + "\u{FFFD}",
924            _ => {
925                let (chunks, remainder) = v.as_chunks::<2>();
926                let string = char::decode_utf16(chunks.iter().copied().map(u16::from_be_bytes))
927                    .map(|r| r.unwrap_or(char::REPLACEMENT_CHARACTER))
928                    .collect();
929                if remainder.is_empty() { string } else { string + "\u{FFFD}" }
930            }
931        }
932    }
933
934    /// Decomposes a `String` into its raw components: `(pointer, length, capacity)`.
935    ///
936    /// Returns the raw pointer to the underlying data, the length of
937    /// the string (in bytes), and the allocated capacity of the data
938    /// (in bytes). These are the same arguments in the same order as
939    /// the arguments to [`from_raw_parts`].
940    ///
941    /// After calling this function, the caller is responsible for the
942    /// memory previously managed by the `String`. The only way to do
943    /// this is to convert the raw pointer, length, and capacity back
944    /// into a `String` with the [`from_raw_parts`] function, allowing
945    /// the destructor to perform the cleanup.
946    ///
947    /// If `capacity == 0`, then `pointer` may be dangling. Otherwise,
948    /// it will always be valid for reads and writes over `capacity`
949    /// bytes, and point to the start of the string.
950    ///
951    /// [`from_raw_parts`]: String::from_raw_parts
952    ///
953    /// # Examples
954    ///
955    /// ```
956    /// let s = String::from("hello");
957    ///
958    /// let (ptr, len, cap) = s.into_raw_parts();
959    ///
960    /// let rebuilt = unsafe { String::from_raw_parts(ptr, len, cap) };
961    /// assert_eq!(rebuilt, "hello");
962    /// ```
963    #[must_use = "losing the pointer will leak memory"]
964    #[stable(feature = "vec_into_raw_parts", since = "1.93.0")]
965    #[inline]
966    pub fn into_raw_parts(self) -> (*mut u8, usize, usize) {
967        self.vec.into_raw_parts()
968    }
969
970    /// Creates a new `String` from a pointer, a length and a capacity.
971    ///
972    /// # Safety
973    ///
974    /// This is highly unsafe, due to the number of invariants that aren't
975    /// checked:
976    ///
977    /// * all safety requirements for [`Vec::<u8>::from_raw_parts`].
978    /// * all safety requirements for [`String::from_utf8_unchecked`].
979    ///
980    /// Violating these may cause problems like corrupting the allocator's
981    /// internal data structures. For example, it is normally **not** safe to
982    /// build a `String` from a pointer to a C `char` array containing UTF-8
983    /// _unless_ you are certain that array was originally allocated by the
984    /// Rust standard library's allocator.
985    ///
986    /// The ownership of `buf` is effectively transferred to the
987    /// `String` which may then deallocate, reallocate or change the
988    /// contents of memory pointed to by the pointer at will. Ensure
989    /// that nothing else uses the pointer after calling this
990    /// function.
991    ///
992    /// # Examples
993    ///
994    /// ```
995    /// unsafe {
996    ///     let s = String::from("hello");
997    ///
998    ///     // Deconstruct the String into parts.
999    ///     let (ptr, len, capacity) = s.into_raw_parts();
1000    ///
1001    ///     let s = String::from_raw_parts(ptr, len, capacity);
1002    ///
1003    ///     assert_eq!(String::from("hello"), s);
1004    /// }
1005    /// ```
1006    #[inline]
1007    #[stable(feature = "rust1", since = "1.0.0")]
1008    pub unsafe fn from_raw_parts(buf: *mut u8, length: usize, capacity: usize) -> String {
1009        // SAFETY: Upheld by caller.
1010        unsafe { String { vec: Vec::from_raw_parts(buf, length, capacity) } }
1011    }
1012
1013    /// Converts a vector of bytes to a `String` without checking that the
1014    /// string contains valid UTF-8.
1015    ///
1016    /// See the safe version, [`from_utf8`], for more details.
1017    ///
1018    /// [`from_utf8`]: String::from_utf8
1019    ///
1020    /// # Safety
1021    ///
1022    /// This function is unsafe because it does not check that the bytes passed
1023    /// to it are valid UTF-8. If this constraint is violated, it may cause
1024    /// memory unsafety issues with future users of the `String`, as the rest of
1025    /// the standard library assumes that `String`s are valid UTF-8.
1026    ///
1027    /// # Examples
1028    ///
1029    /// ```
1030    /// // some bytes, in a vector
1031    /// let sparkle_heart = vec![240, 159, 146, 150];
1032    ///
1033    /// let sparkle_heart = unsafe {
1034    ///     String::from_utf8_unchecked(sparkle_heart)
1035    /// };
1036    ///
1037    /// assert_eq!("πŸ’–", sparkle_heart);
1038    /// ```
1039    #[inline]
1040    #[must_use]
1041    #[stable(feature = "rust1", since = "1.0.0")]
1042    pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String {
1043        String { vec: bytes }
1044    }
1045
1046    /// Converts a `String` into a byte vector.
1047    ///
1048    /// This consumes the `String`, so we do not need to copy its contents.
1049    ///
1050    /// # Examples
1051    ///
1052    /// ```
1053    /// let s = String::from("hello");
1054    /// let bytes = s.into_bytes();
1055    ///
1056    /// assert_eq!(&[104, 101, 108, 108, 111][..], &bytes[..]);
1057    /// ```
1058    #[inline]
1059    #[must_use = "`self` will be dropped if the result is not used"]
1060    #[stable(feature = "rust1", since = "1.0.0")]
1061    #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")]
1062    #[rustc_allow_const_fn_unstable(const_precise_live_drops)]
1063    pub const fn into_bytes(self) -> Vec<u8> {
1064        self.vec
1065    }
1066
1067    /// Extracts a string slice containing the entire `String`.
1068    ///
1069    /// # Examples
1070    ///
1071    /// ```
1072    /// let s = String::from("foo");
1073    ///
1074    /// assert_eq!("foo", s.as_str());
1075    /// ```
1076    #[inline]
1077    #[must_use]
1078    #[stable(feature = "string_as_str", since = "1.7.0")]
1079    #[rustc_diagnostic_item = "string_as_str"]
1080    #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")]
1081    pub const fn as_str(&self) -> &str {
1082        // SAFETY: String contents are stipulated to be valid UTF-8, invalid contents are an error
1083        // at construction.
1084        unsafe { str::from_utf8_unchecked(self.vec.as_slice()) }
1085    }
1086
1087    /// Converts a `String` into a mutable string slice.
1088    ///
1089    /// # Examples
1090    ///
1091    /// ```
1092    /// let mut s = String::from("foobar");
1093    /// let s_mut_str = s.as_mut_str();
1094    ///
1095    /// s_mut_str.make_ascii_uppercase();
1096    ///
1097    /// assert_eq!("FOOBAR", s_mut_str);
1098    /// ```
1099    #[inline]
1100    #[must_use]
1101    #[stable(feature = "string_as_str", since = "1.7.0")]
1102    #[rustc_diagnostic_item = "string_as_mut_str"]
1103    #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")]
1104    pub const fn as_mut_str(&mut self) -> &mut str {
1105        // SAFETY: String contents are stipulated to be valid UTF-8, invalid contents are an error
1106        // at construction.
1107        unsafe { str::from_utf8_unchecked_mut(self.vec.as_mut_slice()) }
1108    }
1109
1110    /// Appends a given string slice onto the end of this `String`.
1111    ///
1112    /// # Panics
1113    ///
1114    /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
1115    ///
1116    /// # Examples
1117    ///
1118    /// ```
1119    /// let mut s = String::from("foo");
1120    ///
1121    /// s.push_str("bar");
1122    ///
1123    /// assert_eq!("foobar", s);
1124    /// ```
1125    #[cfg(not(no_global_oom_handling))]
1126    #[inline]
1127    #[stable(feature = "rust1", since = "1.0.0")]
1128    #[rustc_confusables("append", "push")]
1129    #[rustc_diagnostic_item = "string_push_str"]
1130    pub fn push_str(&mut self, string: &str) {
1131        self.vec.extend_from_slice(string.as_bytes())
1132    }
1133
1134    /// Appends a given string slice onto the end of this `String`, returning
1135    /// [`TryReserveError`] otherwise.
1136    #[cfg_attr(
1137        not(no_global_oom_handling),
1138        expect(
1139            dead_code,
1140            reason = "currently only used in IO module when global OOM handling is disabled"
1141        )
1142    )]
1143    pub(crate) fn try_push_str(&mut self, string: &str) -> Result<(), TryReserveError> {
1144        self.vec.try_extend_from_slice_of_bytes(string.as_bytes())
1145    }
1146
1147    #[cfg(not(no_global_oom_handling))]
1148    #[inline]
1149    fn push_str_slice(&mut self, slice: &[&str]) {
1150        // use saturating arithmetic to ensure that in the case of an overflow, reserve() throws OOM
1151        let additional: Saturating<usize> = slice.iter().map(|x| Saturating(x.len())).sum();
1152        self.reserve(additional.0);
1153        let (ptr, len, cap) = core::mem::take(self).into_raw_parts();
1154        // SAFETY: `self` have reserved enough space for strs in `slice`, and we are copying from valid UTF-8 slices.
1155        // Therefore all unsafe operations are safe.
1156        unsafe {
1157            let mut dst = ptr.add(len);
1158            for new in slice {
1159                core::ptr::copy_nonoverlapping(new.as_ptr(), dst, new.len());
1160                dst = dst.add(new.len());
1161            }
1162            *self = String::from_raw_parts(ptr, len + additional.0, cap);
1163        }
1164    }
1165
1166    /// Copies elements from `src` range to the end of the string.
1167    ///
1168    /// # Panics
1169    ///
1170    /// Panics if the range has `start_bound > end_bound`, if the range is
1171    /// bounded on either end and does not lie on a [`char`] boundary, or if the
1172    /// new capacity exceeds `isize::MAX` bytes.
1173    ///
1174    /// # Examples
1175    ///
1176    /// ```
1177    /// let mut string = String::from("abcde");
1178    ///
1179    /// string.extend_from_within(2..);
1180    /// assert_eq!(string, "abcdecde");
1181    ///
1182    /// string.extend_from_within(..2);
1183    /// assert_eq!(string, "abcdecdeab");
1184    ///
1185    /// string.extend_from_within(4..8);
1186    /// assert_eq!(string, "abcdecdeabecde");
1187    /// ```
1188    #[cfg(not(no_global_oom_handling))]
1189    #[stable(feature = "string_extend_from_within", since = "1.87.0")]
1190    #[track_caller]
1191    pub fn extend_from_within<R>(&mut self, src: R)
1192    where
1193        R: RangeBounds<usize>,
1194    {
1195        let src @ Range { start, end } = slice::range(src, ..self.len());
1196
1197        assert!(self.is_char_boundary(start));
1198        assert!(self.is_char_boundary(end));
1199
1200        self.vec.extend_from_within(src);
1201    }
1202
1203    /// Returns this `String`'s capacity, in bytes.
1204    ///
1205    /// # Examples
1206    ///
1207    /// ```
1208    /// let s = String::with_capacity(10);
1209    ///
1210    /// assert!(s.capacity() >= 10);
1211    /// ```
1212    #[inline]
1213    #[must_use]
1214    #[stable(feature = "rust1", since = "1.0.0")]
1215    #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")]
1216    pub const fn capacity(&self) -> usize {
1217        self.vec.capacity()
1218    }
1219
1220    /// Reserves capacity for at least `additional` bytes more than the
1221    /// current length. The allocator may reserve more space to speculatively
1222    /// avoid frequent allocations. After calling `reserve`,
1223    /// capacity will be greater than or equal to `self.len() + additional`.
1224    /// Does nothing if capacity is already sufficient.
1225    ///
1226    /// # Panics
1227    ///
1228    /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
1229    ///
1230    /// # Examples
1231    ///
1232    /// Basic usage:
1233    ///
1234    /// ```
1235    /// let mut s = String::new();
1236    ///
1237    /// s.reserve(10);
1238    ///
1239    /// assert!(s.capacity() >= 10);
1240    /// ```
1241    ///
1242    /// This might not actually increase the capacity:
1243    ///
1244    /// ```
1245    /// let mut s = String::with_capacity(10);
1246    /// s.push('a');
1247    /// s.push('b');
1248    ///
1249    /// // s now has a length of 2 and a capacity of at least 10
1250    /// let capacity = s.capacity();
1251    /// assert_eq!(2, s.len());
1252    /// assert!(capacity >= 10);
1253    ///
1254    /// // Since we already have at least an extra 8 capacity, calling this...
1255    /// s.reserve(8);
1256    ///
1257    /// // ... doesn't actually increase.
1258    /// assert_eq!(capacity, s.capacity());
1259    /// ```
1260    #[cfg(not(no_global_oom_handling))]
1261    #[inline]
1262    #[stable(feature = "rust1", since = "1.0.0")]
1263    pub fn reserve(&mut self, additional: usize) {
1264        self.vec.reserve(additional)
1265    }
1266
1267    /// Reserves the minimum capacity for at least `additional` bytes more than
1268    /// the current length. Unlike [`reserve`], this will not
1269    /// deliberately over-allocate to speculatively avoid frequent allocations.
1270    /// After calling `reserve_exact`, capacity will be greater than or equal to
1271    /// `self.len() + additional`. Does nothing if the capacity is already
1272    /// sufficient.
1273    ///
1274    /// [`reserve`]: String::reserve
1275    ///
1276    /// # Panics
1277    ///
1278    /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
1279    ///
1280    /// # Examples
1281    ///
1282    /// Basic usage:
1283    ///
1284    /// ```
1285    /// let mut s = String::new();
1286    ///
1287    /// s.reserve_exact(10);
1288    ///
1289    /// assert!(s.capacity() >= 10);
1290    /// ```
1291    ///
1292    /// This might not actually increase the capacity:
1293    ///
1294    /// ```
1295    /// let mut s = String::with_capacity(10);
1296    /// s.push('a');
1297    /// s.push('b');
1298    ///
1299    /// // s now has a length of 2 and a capacity of at least 10
1300    /// let capacity = s.capacity();
1301    /// assert_eq!(2, s.len());
1302    /// assert!(capacity >= 10);
1303    ///
1304    /// // Since we already have at least an extra 8 capacity, calling this...
1305    /// s.reserve_exact(8);
1306    ///
1307    /// // ... doesn't actually increase.
1308    /// assert_eq!(capacity, s.capacity());
1309    /// ```
1310    #[cfg(not(no_global_oom_handling))]
1311    #[inline]
1312    #[stable(feature = "rust1", since = "1.0.0")]
1313    pub fn reserve_exact(&mut self, additional: usize) {
1314        self.vec.reserve_exact(additional)
1315    }
1316
1317    /// Tries to reserve capacity for at least `additional` bytes more than the
1318    /// current length. The allocator may reserve more space to speculatively
1319    /// avoid frequent allocations. After calling `try_reserve`, capacity will be
1320    /// greater than or equal to `self.len() + additional` if it returns
1321    /// `Ok(())`. Does nothing if capacity is already sufficient. This method
1322    /// preserves the contents even if an error occurs.
1323    ///
1324    /// # Errors
1325    ///
1326    /// If the capacity overflows, or the allocator reports a failure, then an error
1327    /// is returned.
1328    ///
1329    /// # Examples
1330    ///
1331    /// ```
1332    /// use std::collections::TryReserveError;
1333    ///
1334    /// fn process_data(data: &str) -> Result<String, TryReserveError> {
1335    ///     let mut output = String::new();
1336    ///
1337    ///     // Pre-reserve the memory, exiting if we can't
1338    ///     output.try_reserve(data.len())?;
1339    ///
1340    ///     // Now we know this can't OOM in the middle of our complex work
1341    ///     output.push_str(data);
1342    ///
1343    ///     Ok(output)
1344    /// }
1345    /// # process_data("rust").expect("reserving capacity for 12 bytes should never fail");
1346    /// ```
1347    #[stable(feature = "try_reserve", since = "1.57.0")]
1348    pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
1349        self.vec.try_reserve(additional)
1350    }
1351
1352    /// Tries to reserve the minimum capacity for at least `additional` bytes
1353    /// more than the current length. Unlike [`try_reserve`], this will not
1354    /// deliberately over-allocate to speculatively avoid frequent allocations.
1355    /// After calling `try_reserve_exact`, capacity will be greater than or
1356    /// equal to `self.len() + additional` if it returns `Ok(())`.
1357    /// Does nothing if the capacity is already sufficient.
1358    ///
1359    /// Note that the allocator may give the collection more space than it
1360    /// requests. Therefore, capacity can not be relied upon to be precisely
1361    /// minimal. Prefer [`try_reserve`] if future insertions are expected.
1362    ///
1363    /// [`try_reserve`]: String::try_reserve
1364    ///
1365    /// # Errors
1366    ///
1367    /// If the capacity overflows, or the allocator reports a failure, then an error
1368    /// is returned.
1369    ///
1370    /// # Examples
1371    ///
1372    /// ```
1373    /// use std::collections::TryReserveError;
1374    ///
1375    /// fn process_data(data: &str) -> Result<String, TryReserveError> {
1376    ///     let mut output = String::new();
1377    ///
1378    ///     // Pre-reserve the memory, exiting if we can't
1379    ///     output.try_reserve_exact(data.len())?;
1380    ///
1381    ///     // Now we know this can't OOM in the middle of our complex work
1382    ///     output.push_str(data);
1383    ///
1384    ///     Ok(output)
1385    /// }
1386    /// # process_data("rust").expect("reserving capacity for 12 bytes should never fail");
1387    /// ```
1388    #[stable(feature = "try_reserve", since = "1.57.0")]
1389    pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
1390        self.vec.try_reserve_exact(additional)
1391    }
1392
1393    /// Shrinks the capacity of this `String` to match its length.
1394    ///
1395    /// # Examples
1396    ///
1397    /// ```
1398    /// let mut s = String::from("foo");
1399    ///
1400    /// s.reserve(100);
1401    /// assert!(s.capacity() >= 100);
1402    ///
1403    /// s.shrink_to_fit();
1404    /// assert_eq!(3, s.capacity());
1405    /// ```
1406    #[cfg(not(no_global_oom_handling))]
1407    #[inline]
1408    #[stable(feature = "rust1", since = "1.0.0")]
1409    pub fn shrink_to_fit(&mut self) {
1410        self.vec.shrink_to_fit()
1411    }
1412
1413    /// Shrinks the capacity of this `String` with a lower bound.
1414    ///
1415    /// The capacity will remain at least as large as both the length
1416    /// and the supplied value.
1417    ///
1418    /// If the current capacity is less than the lower limit, this is a no-op.
1419    ///
1420    /// # Examples
1421    ///
1422    /// ```
1423    /// let mut s = String::from("foo");
1424    ///
1425    /// s.reserve(100);
1426    /// assert!(s.capacity() >= 100);
1427    ///
1428    /// s.shrink_to(10);
1429    /// assert!(s.capacity() >= 10);
1430    /// s.shrink_to(0);
1431    /// assert!(s.capacity() >= 3);
1432    /// ```
1433    #[cfg(not(no_global_oom_handling))]
1434    #[inline]
1435    #[stable(feature = "shrink_to", since = "1.56.0")]
1436    pub fn shrink_to(&mut self, min_capacity: usize) {
1437        self.vec.shrink_to(min_capacity)
1438    }
1439
1440    /// Appends the given [`char`] to the end of this `String`.
1441    ///
1442    /// # Panics
1443    ///
1444    /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
1445    ///
1446    /// # Examples
1447    ///
1448    /// ```
1449    /// let mut s = String::from("abc");
1450    ///
1451    /// s.push('1');
1452    /// s.push('2');
1453    /// s.push('3');
1454    ///
1455    /// assert_eq!("abc123", s);
1456    /// ```
1457    #[cfg(not(no_global_oom_handling))]
1458    #[inline]
1459    #[stable(feature = "rust1", since = "1.0.0")]
1460    pub fn push(&mut self, ch: char) {
1461        let len = self.len();
1462        let ch_len = ch.len_utf8();
1463        self.reserve(ch_len);
1464
1465        // SAFETY: Just reserved capacity for at least the length needed to encode `ch`.
1466        unsafe {
1467            core::char::encode_utf8_raw_unchecked(ch as u32, self.vec.as_mut_ptr().add(len));
1468            self.vec.set_len(len + ch_len);
1469        }
1470    }
1471
1472    /// Returns a byte slice of this `String`'s contents.
1473    ///
1474    /// The inverse of this method is [`from_utf8`].
1475    ///
1476    /// [`from_utf8`]: String::from_utf8
1477    ///
1478    /// # Examples
1479    ///
1480    /// ```
1481    /// let s = String::from("hello");
1482    ///
1483    /// assert_eq!(&[104, 101, 108, 108, 111], s.as_bytes());
1484    /// ```
1485    #[inline]
1486    #[must_use]
1487    #[stable(feature = "rust1", since = "1.0.0")]
1488    #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")]
1489    pub const fn as_bytes(&self) -> &[u8] {
1490        self.vec.as_slice()
1491    }
1492
1493    /// Shortens this `String` to the specified length.
1494    ///
1495    /// If `new_len` is greater than or equal to the string's current length,
1496    /// this has no effect.
1497    ///
1498    /// Note that this method has no effect on the allocated capacity
1499    /// of the string
1500    ///
1501    /// # Panics
1502    ///
1503    /// Panics if `new_len` does not lie on a [`char`] boundary.
1504    ///
1505    /// # Examples
1506    ///
1507    /// ```
1508    /// let mut s = String::from("hello");
1509    ///
1510    /// s.truncate(2);
1511    ///
1512    /// assert_eq!("he", s);
1513    /// ```
1514    #[inline]
1515    #[stable(feature = "rust1", since = "1.0.0")]
1516    #[track_caller]
1517    pub fn truncate(&mut self, new_len: usize) {
1518        if new_len >= self.len() {
1519            return;
1520        }
1521        assert!(self.is_char_boundary(new_len));
1522        self.vec.truncate(new_len)
1523    }
1524
1525    /// Removes the last character from the string buffer and returns it.
1526    ///
1527    /// Returns [`None`] if this `String` is empty.
1528    ///
1529    /// # Examples
1530    ///
1531    /// ```
1532    /// let mut s = String::from("abč");
1533    ///
1534    /// assert_eq!(s.pop(), Some('č'));
1535    /// assert_eq!(s.pop(), Some('b'));
1536    /// assert_eq!(s.pop(), Some('a'));
1537    ///
1538    /// assert_eq!(s.pop(), None);
1539    /// ```
1540    #[inline]
1541    #[stable(feature = "rust1", since = "1.0.0")]
1542    pub fn pop(&mut self) -> Option<char> {
1543        let ch = self.chars().rev().next()?;
1544        let newlen = self.len() - ch.len_utf8();
1545        // SAFETY: `newlen` is less than old length.
1546        unsafe {
1547            self.vec.set_len(newlen);
1548        }
1549        Some(ch)
1550    }
1551
1552    /// Removes a [`char`] from this `String` at byte position `idx` and returns it.
1553    ///
1554    /// Copies all bytes after the removed char to new positions.
1555    ///
1556    /// Note that calling this in a loop can result in quadratic behavior.
1557    ///
1558    /// # Panics
1559    ///
1560    /// Panics if `idx` is larger than or equal to the `String`'s length,
1561    /// or if it does not lie on a [`char`] boundary.
1562    ///
1563    /// # Examples
1564    ///
1565    /// ```
1566    /// let mut s = String::from("abΓ§");
1567    ///
1568    /// assert_eq!(s.remove(0), 'a');
1569    /// assert_eq!(s.remove(1), 'Γ§');
1570    /// assert_eq!(s.remove(0), 'b');
1571    /// ```
1572    #[inline]
1573    #[stable(feature = "rust1", since = "1.0.0")]
1574    #[track_caller]
1575    #[rustc_confusables("delete", "take")]
1576    pub fn remove(&mut self, idx: usize) -> char {
1577        let ch = match self[idx..].chars().next() {
1578            Some(ch) => ch,
1579            None => panic!("cannot remove a char from the end of a string"),
1580        };
1581
1582        let next = idx + ch.len_utf8();
1583        let len = self.len();
1584        // SAFETY:
1585        // * Since `next` is not bigger than `len`, `self.vec.as_ptr().add(next)`
1586        //   is valid for reads and `self.vec.as_mut_ptr().add(idx)` is valid for writes.
1587        //   Both pointers are valid for `len - next` bytes.
1588        // * new length is less than old length.
1589        unsafe {
1590            ptr::copy(self.vec.as_ptr().add(next), self.vec.as_mut_ptr().add(idx), len - next);
1591            self.vec.set_len(len - (next - idx));
1592        }
1593        ch
1594    }
1595
1596    /// Remove all matches of pattern `pat` in the `String`.
1597    ///
1598    /// # Examples
1599    ///
1600    /// ```
1601    /// #![feature(string_remove_matches)]
1602    /// let mut s = String::from("Trees are not green, the sky is not blue.");
1603    /// s.remove_matches("not ");
1604    /// assert_eq!("Trees are green, the sky is blue.", s);
1605    /// ```
1606    ///
1607    /// Matches will be detected and removed iteratively, so in cases where
1608    /// patterns overlap, only the first pattern will be removed:
1609    ///
1610    /// ```
1611    /// #![feature(string_remove_matches)]
1612    /// let mut s = String::from("banana");
1613    /// s.remove_matches("ana");
1614    /// assert_eq!("bna", s);
1615    /// ```
1616    #[cfg(not(no_global_oom_handling))]
1617    #[unstable(feature = "string_remove_matches", issue = "72826")]
1618    pub fn remove_matches<P: Pattern>(&mut self, pat: P) {
1619        use core::str::pattern::Searcher;
1620
1621        let rejections = {
1622            let mut searcher = pat.into_searcher(self);
1623            // Per Searcher::next:
1624            //
1625            // A Match result needs to contain the whole matched pattern,
1626            // however Reject results may be split up into arbitrary many
1627            // adjacent fragments. Both ranges may have zero length.
1628            //
1629            // In practice the implementation of Searcher::next_match tends to
1630            // be more efficient, so we use it here and do some work to invert
1631            // matches into rejections since that's what we want to copy below.
1632            let mut front = 0;
1633            let rejections: Vec<_> = from_fn(|| {
1634                let (start, end) = searcher.next_match()?;
1635                let prev_front = front;
1636                front = end;
1637                Some((prev_front, start))
1638            })
1639            .collect();
1640            rejections.into_iter().chain(core::iter::once((front, self.len())))
1641        };
1642
1643        let mut len = 0;
1644        let ptr = self.vec.as_mut_ptr();
1645
1646        for (start, end) in rejections {
1647            let count = end - start;
1648            if start != len {
1649                // SAFETY: per Searcher::next:
1650                //
1651                // The stream of Match and Reject values up to a Done will
1652                // contain index ranges that are adjacent, non-overlapping,
1653                // covering the whole haystack, and laying on utf8
1654                // boundaries.
1655                unsafe {
1656                    ptr::copy(ptr.add(start), ptr.add(len), count);
1657                }
1658            }
1659            len += count;
1660        }
1661
1662        // SAFETY: `len` is less than or equal to the original length of the string.
1663        unsafe {
1664            self.vec.set_len(len);
1665        }
1666    }
1667
1668    /// Retains only the characters specified by the predicate.
1669    ///
1670    /// In other words, remove all characters `c` such that `f(c)` returns `false`.
1671    /// This method operates in place, visiting each character exactly once in the
1672    /// original order, and preserves the order of the retained characters.
1673    ///
1674    /// # Examples
1675    ///
1676    /// ```
1677    /// let mut s = String::from("f_o_ob_ar");
1678    ///
1679    /// s.retain(|c| c != '_');
1680    ///
1681    /// assert_eq!(s, "foobar");
1682    /// ```
1683    ///
1684    /// Because the elements are visited exactly once in the original order,
1685    /// external state may be used to decide which elements to keep.
1686    ///
1687    /// ```
1688    /// let mut s = String::from("abcde");
1689    /// let keep = [false, true, true, false, true];
1690    /// let mut iter = keep.iter();
1691    /// s.retain(|_| *iter.next().unwrap());
1692    /// assert_eq!(s, "bce");
1693    /// ```
1694    #[inline]
1695    #[stable(feature = "string_retain", since = "1.26.0")]
1696    pub fn retain<F>(&mut self, mut f: F)
1697    where
1698        F: FnMut(char) -> bool,
1699    {
1700        let len = self.len();
1701        if len == 0 {
1702            // Explicit check results in better optimization
1703            return;
1704        }
1705
1706        struct PanicGuard<'a> {
1707            s: &'a mut String,
1708            write: usize,
1709        }
1710
1711        impl Drop for PanicGuard<'_> {
1712            fn drop(&mut self) {
1713                debug_assert!(self.write <= self.s.len());
1714                debug_assert!(str::from_utf8(&self.s.vec[..self.write]).is_ok());
1715                // SAFETY: Restore the string length to the number of bytes written so far.
1716                unsafe { self.s.vec.set_len(self.write) }
1717            }
1718        }
1719
1720        // Fast path: find the first character that should be removed or return early.
1721        let mut chars = self.char_indices();
1722        let (mut read, write) = loop {
1723            let Some((idx, ch)) = chars.next() else { return };
1724            if hint::unlikely(!f(ch)) {
1725                break (idx + ch.len_utf8(), idx);
1726            }
1727        };
1728        drop(chars);
1729
1730        // Slow path: at least one character is going to be removed.
1731        let mut g = PanicGuard { s: self, write };
1732        while read < len {
1733            // SAFETY: `read` is within bound because `read` < `len`, so taking
1734            // a slice with `len` is safe.
1735            let ch = unsafe { g.s.get_unchecked(read..len).chars().next().unwrap_unchecked() };
1736            let ch_len = ch.len_utf8();
1737            if f(ch) {
1738                // SAFETY: `read` is on a char boundary, as guaranteed above; `g.write` is
1739                // within bounds because it is always behind `read`.
1740                unsafe {
1741                    let ptr = g.s.vec.as_mut_ptr();
1742                    ptr::copy(ptr.add(read), ptr.add(g.write), ch_len);
1743                }
1744                g.write += ch_len;
1745            }
1746            read += ch_len;
1747        }
1748
1749        // All bytes processed; commit the final length by dropping the guard.
1750        drop(g);
1751    }
1752
1753    /// Inserts a character into this `String` at byte position `idx`.
1754    ///
1755    /// Reallocates if `self.capacity()` is insufficient, which may involve copying all
1756    /// `self.capacity()` bytes. Makes space for the insertion by copying all bytes of
1757    /// `&self[idx..]` to new positions.
1758    ///
1759    /// Note that calling this in a loop can result in quadratic behavior.
1760    ///
1761    /// # Panics
1762    ///
1763    /// Panics if `idx` is larger than the `String`'s length, or if it does not
1764    /// lie on a [`char`] boundary.
1765    ///
1766    /// # Examples
1767    ///
1768    /// ```
1769    /// let mut s = String::with_capacity(3);
1770    ///
1771    /// s.insert(0, 'f');
1772    /// s.insert(1, 'o');
1773    /// s.insert(2, 'o');
1774    ///
1775    /// assert_eq!("foo", s);
1776    /// ```
1777    #[cfg(not(no_global_oom_handling))]
1778    #[inline]
1779    #[track_caller]
1780    #[stable(feature = "rust1", since = "1.0.0")]
1781    #[rustc_confusables("set")]
1782    pub fn insert(&mut self, idx: usize, ch: char) {
1783        assert!(self.is_char_boundary(idx));
1784
1785        let len = self.len();
1786        let ch_len = ch.len_utf8();
1787        self.reserve(ch_len);
1788
1789        // SAFETY: Move the bytes starting from `idx` to their new location `ch_len`
1790        // bytes ahead. This is safe because sufficient capacity was reserved, and `idx`
1791        // is a char boundary.
1792        unsafe {
1793            ptr::copy(
1794                self.vec.as_ptr().add(idx),
1795                self.vec.as_mut_ptr().add(idx + ch_len),
1796                len - idx,
1797            );
1798        }
1799
1800        // SAFETY: Encode the character into the vacated region if `idx != len`,
1801        // or into the uninitialized spare capacity otherwise.
1802        unsafe {
1803            core::char::encode_utf8_raw_unchecked(ch as u32, self.vec.as_mut_ptr().add(idx));
1804        }
1805
1806        // SAFETY: Update the length to include the newly added bytes.
1807        unsafe {
1808            self.vec.set_len(len + ch_len);
1809        }
1810    }
1811
1812    /// Inserts a string slice into this `String` at byte position `idx`.
1813    ///
1814    /// Reallocates if `self.capacity()` is insufficient, which may involve copying all
1815    /// `self.capacity()` bytes. Makes space for the insertion by copying all bytes of
1816    /// `&self[idx..]` to new positions.
1817    ///
1818    /// Note that calling this in a loop can result in quadratic behavior.
1819    ///
1820    /// # Panics
1821    ///
1822    /// Panics if `idx` is larger than the `String`'s length, or if it does not
1823    /// lie on a [`char`] boundary.
1824    ///
1825    /// # Examples
1826    ///
1827    /// ```
1828    /// let mut s = String::from("bar");
1829    ///
1830    /// s.insert_str(0, "foo");
1831    ///
1832    /// assert_eq!("foobar", s);
1833    /// ```
1834    #[cfg(not(no_global_oom_handling))]
1835    #[inline]
1836    #[track_caller]
1837    #[stable(feature = "insert_str", since = "1.16.0")]
1838    #[rustc_diagnostic_item = "string_insert_str"]
1839    pub fn insert_str(&mut self, idx: usize, string: &str) {
1840        assert!(self.is_char_boundary(idx));
1841
1842        let len = self.len();
1843        let amt = string.len();
1844        self.reserve(amt);
1845
1846        // SAFETY: Move the bytes starting from `idx` to their new location `amt` bytes
1847        // ahead. This is safe because sufficient capacity was just reserved, and `idx`
1848        // is a char boundary.
1849        unsafe {
1850            ptr::copy(self.vec.as_ptr().add(idx), self.vec.as_mut_ptr().add(idx + amt), len - idx);
1851        }
1852
1853        // SAFETY: Copy the new string slice into the vacated region if `idx != len`,
1854        // or into the uninitialized spare capacity otherwise. The borrow checker
1855        // ensures that the source and destination do not overlap.
1856        unsafe {
1857            ptr::copy_nonoverlapping(string.as_ptr(), self.vec.as_mut_ptr().add(idx), amt);
1858        }
1859
1860        // SAFETY: Update the length to include the newly added bytes.
1861        unsafe {
1862            self.vec.set_len(len + amt);
1863        }
1864    }
1865
1866    /// Returns a mutable reference to the contents of this `String`.
1867    ///
1868    /// # Safety
1869    ///
1870    /// This function is unsafe because the returned `&mut Vec` allows writing
1871    /// bytes which are not valid UTF-8. If this constraint is violated, using
1872    /// the original `String` after dropping the `&mut Vec` may violate memory
1873    /// safety, as the rest of the standard library assumes that `String`s are
1874    /// valid UTF-8.
1875    ///
1876    /// # Examples
1877    ///
1878    /// ```
1879    /// let mut s = String::from("hello");
1880    ///
1881    /// unsafe {
1882    ///     let vec = s.as_mut_vec();
1883    ///     assert_eq!(&[104, 101, 108, 108, 111][..], &vec[..]);
1884    ///
1885    ///     vec.reverse();
1886    /// }
1887    /// assert_eq!(s, "olleh");
1888    /// ```
1889    #[inline]
1890    #[stable(feature = "rust1", since = "1.0.0")]
1891    #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")]
1892    pub const unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1893        &mut self.vec
1894    }
1895
1896    /// Returns the length of this `String`, in bytes, not [`char`]s or
1897    /// graphemes. In other words, it might not be what a human considers the
1898    /// length of the string.
1899    ///
1900    /// # Examples
1901    ///
1902    /// ```
1903    /// let a = String::from("foo");
1904    /// assert_eq!(a.len(), 3);
1905    ///
1906    /// let fancy_f = String::from("Ζ’oo");
1907    /// assert_eq!(fancy_f.len(), 4);
1908    /// assert_eq!(fancy_f.chars().count(), 3);
1909    /// ```
1910    #[inline]
1911    #[must_use]
1912    #[stable(feature = "rust1", since = "1.0.0")]
1913    #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")]
1914    #[rustc_confusables("length", "size")]
1915    #[rustc_no_implicit_autorefs]
1916    pub const fn len(&self) -> usize {
1917        self.vec.len()
1918    }
1919
1920    /// Returns `true` if this `String` has a length of zero, and `false` otherwise.
1921    ///
1922    /// # Examples
1923    ///
1924    /// ```
1925    /// let mut v = String::new();
1926    /// assert!(v.is_empty());
1927    ///
1928    /// v.push('a');
1929    /// assert!(!v.is_empty());
1930    /// ```
1931    #[inline]
1932    #[must_use]
1933    #[stable(feature = "rust1", since = "1.0.0")]
1934    #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")]
1935    #[rustc_no_implicit_autorefs]
1936    pub const fn is_empty(&self) -> bool {
1937        self.len() == 0
1938    }
1939
1940    /// Splits the string into two at the given byte index.
1941    ///
1942    /// Returns a newly allocated `String`. `self` contains bytes `[0, at)`, and
1943    /// the returned `String` contains bytes `[at, len)`. `at` must be on the
1944    /// boundary of a UTF-8 code point.
1945    ///
1946    /// Note that the capacity of `self` does not change.
1947    ///
1948    /// # Panics
1949    ///
1950    /// Panics if `at` is not on a `UTF-8` code point boundary, or if it is beyond the last
1951    /// code point of the string.
1952    ///
1953    /// # Examples
1954    ///
1955    /// ```
1956    /// # fn main() {
1957    /// let mut hello = String::from("Hello, World!");
1958    /// let world = hello.split_off(7);
1959    /// assert_eq!(hello, "Hello, ");
1960    /// assert_eq!(world, "World!");
1961    /// # }
1962    /// ```
1963    #[cfg(not(no_global_oom_handling))]
1964    #[inline]
1965    #[track_caller]
1966    #[stable(feature = "string_split_off", since = "1.16.0")]
1967    #[must_use = "use `.truncate()` if you don't need the other half"]
1968    pub fn split_off(&mut self, at: usize) -> String {
1969        assert!(self.is_char_boundary(at));
1970        let other = self.vec.split_off(at);
1971        // SAFETY: `other` contains only valid UTF-8 because `at` is on a `UTF-8` code point boundary.
1972        unsafe { String::from_utf8_unchecked(other) }
1973    }
1974
1975    /// Truncates this `String`, removing all contents.
1976    ///
1977    /// While this means the `String` will have a length of zero, it does not
1978    /// touch its capacity.
1979    ///
1980    /// # Examples
1981    ///
1982    /// ```
1983    /// let mut s = String::from("foo");
1984    ///
1985    /// s.clear();
1986    ///
1987    /// assert!(s.is_empty());
1988    /// assert_eq!(0, s.len());
1989    /// assert_eq!(3, s.capacity());
1990    /// ```
1991    #[inline]
1992    #[stable(feature = "rust1", since = "1.0.0")]
1993    pub fn clear(&mut self) {
1994        self.vec.clear()
1995    }
1996
1997    /// Removes the specified range from the string in bulk, returning all
1998    /// removed characters as an iterator.
1999    ///
2000    /// The returned iterator keeps a mutable borrow on the string to optimize
2001    /// its implementation.
2002    ///
2003    /// # Panics
2004    ///
2005    /// Panics if the range has `start_bound > end_bound`, or, if the range is
2006    /// bounded on either end and does not lie on a [`char`] boundary.
2007    ///
2008    /// # Leaking
2009    ///
2010    /// If the returned iterator goes out of scope without being dropped (due to
2011    /// [`core::mem::forget`], for example), the string may still contain a copy
2012    /// of any drained characters, or may have lost characters arbitrarily,
2013    /// including characters outside the range.
2014    ///
2015    /// # Examples
2016    ///
2017    /// ```
2018    /// let mut s = String::from("Ξ± is alpha, Ξ² is beta");
2019    /// let beta_offset = s.find('Ξ²').unwrap_or(s.len());
2020    ///
2021    /// // Remove the range up until the Ξ² from the string
2022    /// let t: String = s.drain(..beta_offset).collect();
2023    /// assert_eq!(t, "Ξ± is alpha, ");
2024    /// assert_eq!(s, "Ξ² is beta");
2025    ///
2026    /// // A full range clears the string, like `clear()` does
2027    /// s.drain(..);
2028    /// assert_eq!(s, "");
2029    /// ```
2030    #[stable(feature = "drain", since = "1.6.0")]
2031    #[track_caller]
2032    pub fn drain<R>(&mut self, range: R) -> Drain<'_>
2033    where
2034        R: RangeBounds<usize>,
2035    {
2036        // Memory safety
2037        //
2038        // The String version of Drain does not have the memory safety issues
2039        // of the vector version. The data is just plain bytes.
2040        // Because the range removal happens in Drop, if the Drain iterator is leaked,
2041        // the removal will not happen.
2042        let Range { start, end } = slice::range(range, ..self.len());
2043        assert!(self.is_char_boundary(start));
2044        assert!(self.is_char_boundary(end));
2045
2046        // Take out two simultaneous borrows. The &mut String won't be accessed
2047        // until iteration is over, in Drop.
2048        let self_ptr = self as *mut _;
2049        // SAFETY: `slice::range` and `is_char_boundary` do the appropriate bounds checks.
2050        let chars_iter = unsafe { self.get_unchecked(start..end) }.chars();
2051
2052        Drain { start, end, iter: chars_iter, string: self_ptr }
2053    }
2054
2055    /// Converts a `String` into an iterator over the [`char`]s of the string.
2056    ///
2057    /// As a string consists of valid UTF-8, we can iterate through a string
2058    /// by [`char`]. This method returns such an iterator.
2059    ///
2060    /// It's important to remember that [`char`] represents a Unicode Scalar
2061    /// Value, and might not match your idea of what a 'character' is. Iteration
2062    /// over grapheme clusters may be what you actually want. That functionality
2063    /// is not provided by Rust's standard library, check crates.io instead.
2064    ///
2065    /// # Examples
2066    ///
2067    /// Basic usage:
2068    ///
2069    /// ```
2070    /// let word = String::from("goodbye");
2071    ///
2072    /// let mut chars = word.into_chars();
2073    ///
2074    /// assert_eq!(Some('g'), chars.next());
2075    /// assert_eq!(Some('o'), chars.next());
2076    /// assert_eq!(Some('o'), chars.next());
2077    /// assert_eq!(Some('d'), chars.next());
2078    /// assert_eq!(Some('b'), chars.next());
2079    /// assert_eq!(Some('y'), chars.next());
2080    /// assert_eq!(Some('e'), chars.next());
2081    ///
2082    /// assert_eq!(None, chars.next());
2083    /// ```
2084    ///
2085    /// Remember, [`char`]s might not match your intuition about characters:
2086    ///
2087    /// ```
2088    /// let y = String::from("y̆");
2089    ///
2090    /// let mut chars = y.into_chars();
2091    ///
2092    /// assert_eq!(Some('y'), chars.next()); // not 'y̆'
2093    /// assert_eq!(Some('\u{0306}'), chars.next());
2094    ///
2095    /// assert_eq!(None, chars.next());
2096    /// ```
2097    ///
2098    /// [`char`]: prim@char
2099    #[inline]
2100    #[must_use = "`self` will be dropped if the result is not used"]
2101    #[stable(feature = "string_into_chars", since = "CURRENT_RUSTC_VERSION")]
2102    pub fn into_chars(self) -> IntoChars {
2103        IntoChars { bytes: self.into_bytes().into_iter() }
2104    }
2105
2106    /// Removes the specified range in the string,
2107    /// and replaces it with the given string.
2108    /// The given string doesn't need to be the same length as the range.
2109    ///
2110    /// # Panics
2111    ///
2112    /// Panics if the range has `start_bound > end_bound`, or, if the range is
2113    /// bounded on either end and does not lie on a [`char`] boundary.
2114    ///
2115    /// # Examples
2116    ///
2117    /// ```
2118    /// let mut s = String::from("Ξ± is alpha, Ξ² is beta");
2119    /// let beta_offset = s.find('Ξ²').unwrap_or(s.len());
2120    ///
2121    /// // Replace the range up until the Ξ² from the string
2122    /// s.replace_range(..beta_offset, "Ξ‘ is capital alpha; ");
2123    /// assert_eq!(s, "Ξ‘ is capital alpha; Ξ² is beta");
2124    /// ```
2125    #[cfg(not(no_global_oom_handling))]
2126    #[stable(feature = "splice", since = "1.27.0")]
2127    #[track_caller]
2128    pub fn replace_range<R>(&mut self, range: R, replace_with: &str)
2129    where
2130        R: RangeBounds<usize>,
2131    {
2132        // We avoid #81138 (nondeterministic RangeBounds impls) because we only use `range` once, here.
2133        let checked_range = slice::range(range, ..self.len());
2134
2135        assert!(
2136            self.is_char_boundary(checked_range.start),
2137            "start of range should be a character boundary"
2138        );
2139        assert!(
2140            self.is_char_boundary(checked_range.end),
2141            "end of range should be a character boundary"
2142        );
2143
2144        if replace_with.len() > checked_range.len() {
2145            self.reserve(replace_with.len() - checked_range.len());
2146        }
2147        // SAFETY: We ensure that we're not replacing across a char boundary and
2148        // that the new contents are valid UTF-8. The only potentially-unsound
2149        // unwind from `splice` that would leave the string in an invalid state
2150        // would be from an error growing the allocation, which we protect against
2151        // by reserving it preemptively.
2152        unsafe { self.as_mut_vec() }.splice(checked_range, replace_with.bytes());
2153    }
2154
2155    /// Replaces the leftmost occurrence of a pattern with another string, in-place.
2156    ///
2157    /// This method can be preferred over [`string = string.replacen(..., 1);`][replacen],
2158    /// as it can use the `String`'s existing capacity to prevent a reallocation if
2159    /// sufficient space is available.
2160    ///
2161    /// # Examples
2162    ///
2163    /// Basic usage:
2164    ///
2165    /// ```
2166    /// #![feature(string_replace_in_place)]
2167    ///
2168    /// let mut s = String::from("Test Results: ❌❌❌");
2169    ///
2170    /// // Replace the leftmost ❌ with a βœ…
2171    /// s.replace_first('❌', "βœ…");
2172    /// assert_eq!(s, "Test Results: βœ…βŒβŒ");
2173    /// ```
2174    ///
2175    /// [replacen]: ../../std/primitive.str.html#method.replacen
2176    #[cfg(not(no_global_oom_handling))]
2177    #[unstable(feature = "string_replace_in_place", issue = "147949")]
2178    pub fn replace_first<P: Pattern>(&mut self, from: P, to: &str) {
2179        let range = match self.match_indices(from).next() {
2180            Some((start, match_str)) => start..start + match_str.len(),
2181            None => return,
2182        };
2183
2184        self.replace_range(range, to);
2185    }
2186
2187    /// Replaces the rightmost occurrence of a pattern with another string, in-place.
2188    ///
2189    /// # Examples
2190    ///
2191    /// Basic usage:
2192    ///
2193    /// ```
2194    /// #![feature(string_replace_in_place)]
2195    ///
2196    /// let mut s = String::from("Test Results: ❌❌❌");
2197    ///
2198    /// // Replace the rightmost ❌ with a βœ…
2199    /// s.replace_last('❌', "βœ…");
2200    /// assert_eq!(s, "Test Results: βŒβŒβœ…");
2201    /// ```
2202    #[cfg(not(no_global_oom_handling))]
2203    #[unstable(feature = "string_replace_in_place", issue = "147949")]
2204    pub fn replace_last<P: Pattern>(&mut self, from: P, to: &str)
2205    where
2206        for<'a> P::Searcher<'a>: core::str::pattern::ReverseSearcher<'a>,
2207    {
2208        let range = match self.rmatch_indices(from).next() {
2209            Some((start, match_str)) => start..start + match_str.len(),
2210            None => return,
2211        };
2212
2213        self.replace_range(range, to);
2214    }
2215
2216    /// Converts this `String` into a <code>[Box]<[str]></code>.
2217    ///
2218    /// Before doing the conversion, this method discards excess capacity like [`shrink_to_fit`].
2219    /// Note that this call may reallocate and copy the bytes of the string.
2220    ///
2221    /// [`shrink_to_fit`]: String::shrink_to_fit
2222    /// [str]: prim@str "str"
2223    ///
2224    /// # Examples
2225    ///
2226    /// ```
2227    /// let s = String::from("hello");
2228    ///
2229    /// let b = s.into_boxed_str();
2230    /// ```
2231    #[cfg(not(no_global_oom_handling))]
2232    #[stable(feature = "box_str", since = "1.4.0")]
2233    #[must_use = "`self` will be dropped if the result is not used"]
2234    #[inline]
2235    pub fn into_boxed_str(self) -> Box<str> {
2236        let slice = self.vec.into_boxed_slice();
2237        // SAFETY: `slice` contains only valid UTF-8 because `String` is guaranteed to be valid UTF-8.
2238        unsafe { from_boxed_utf8_unchecked(slice) }
2239    }
2240
2241    /// Consumes and leaks the `String`, returning a mutable reference to the contents,
2242    /// `&'a mut str`.
2243    ///
2244    /// The caller has free choice over the returned lifetime, including `'static`. Indeed,
2245    /// this function is ideally used for data that lives for the remainder of the program's life,
2246    /// as dropping the returned reference will cause a memory leak.
2247    ///
2248    /// It does not reallocate or shrink the `String`, so the leaked allocation may include unused
2249    /// capacity that is not part of the returned slice. If you want to discard excess capacity,
2250    /// call [`into_boxed_str`], and then [`Box::leak`] instead. However, keep in mind that
2251    /// trimming the capacity may result in a reallocation and copy.
2252    ///
2253    /// [`into_boxed_str`]: Self::into_boxed_str
2254    ///
2255    /// # Examples
2256    ///
2257    /// ```
2258    /// let x = String::from("bucket");
2259    /// let static_ref: &'static mut str = x.leak();
2260    /// assert_eq!(static_ref, "bucket");
2261    /// # // FIXME(https://github.com/rust-lang/miri/issues/3670):
2262    /// # // use -Zmiri-disable-leak-check instead of unleaking in tests meant to leak.
2263    /// # drop(unsafe { Box::from_raw(static_ref) });
2264    /// ```
2265    #[stable(feature = "string_leak", since = "1.72.0")]
2266    #[inline]
2267    pub fn leak<'a>(self) -> &'a mut str {
2268        let slice = self.vec.leak();
2269        // SAFETY: `slice` contains only valid UTF-8 because `String` is guaranteed to be valid UTF-8.
2270        unsafe { from_utf8_unchecked_mut(slice) }
2271    }
2272}
2273
2274impl FromUtf8Error {
2275    /// Returns a slice of [`u8`]s bytes that were attempted to convert to a `String`.
2276    ///
2277    /// # Examples
2278    ///
2279    /// ```
2280    /// // some invalid bytes, in a vector
2281    /// let bytes = vec![0, 159];
2282    ///
2283    /// let value = String::from_utf8(bytes);
2284    ///
2285    /// assert_eq!(&[0, 159], value.unwrap_err().as_bytes());
2286    /// ```
2287    #[must_use]
2288    #[stable(feature = "from_utf8_error_as_bytes", since = "1.26.0")]
2289    pub fn as_bytes(&self) -> &[u8] {
2290        &self.bytes[..]
2291    }
2292
2293    /// Converts the bytes into a `String` lossily, substituting invalid UTF-8
2294    /// sequences with replacement characters.
2295    ///
2296    /// See [`String::from_utf8_lossy`] for more details on replacement of
2297    /// invalid sequences, and [`String::from_utf8_lossy_owned`] for the
2298    /// `String` function which corresponds to this function.
2299    ///
2300    /// This is useful in conjunction with [`String::from_utf8`] when you need
2301    /// to branch on whether the bytes are valid UTF-8, but still want to
2302    /// recover a lossily converted `String` in the error case. Use
2303    /// [`String::from_utf8_lossy_owned`] if you always need a lossily converted
2304    /// `String`.
2305    ///
2306    /// Since the original [`String::from_utf8`] error records where validation
2307    /// stopped, this method does not need to re-check the already valid prefix
2308    /// of the byte sequence.
2309    ///
2310    /// # Examples
2311    ///
2312    /// ```
2313    /// // some invalid bytes
2314    /// let input: Vec<u8> = b"Hello \xF0\x90\x80World".into();
2315    ///
2316    /// let (output, had_invalid_utf8) = match String::from_utf8(input) {
2317    ///     Ok(output) => (output, false),
2318    ///     Err(error) => {
2319    ///         // The bytes were not valid UTF-8, but we can still recover a string.
2320    ///         (error.into_utf8_lossy(), true)
2321    ///     }
2322    /// };
2323    ///
2324    /// assert_eq!(String::from("Hello οΏ½World"), output);
2325    /// assert!(had_invalid_utf8);
2326    /// ```
2327    #[must_use]
2328    #[cfg(not(no_global_oom_handling))]
2329    #[stable(feature = "string_from_utf8_lossy_owned", since = "1.99.0")]
2330    pub fn into_utf8_lossy(self) -> String {
2331        const REPLACEMENT: &str = "\u{FFFD}";
2332
2333        let mut res = {
2334            let mut v = Vec::with_capacity(self.bytes.len());
2335
2336            // `Utf8Error::valid_up_to` returns the maximum index of validated
2337            // UTF-8 bytes. Copy the valid bytes into the output buffer.
2338            v.extend_from_slice(&self.bytes[..self.error.valid_up_to()]);
2339
2340            // SAFETY: This is safe because the only bytes present in the buffer
2341            // were validated as UTF-8 by the call to `String::from_utf8` which
2342            // produced this `FromUtf8Error`.
2343            unsafe { String::from_utf8_unchecked(v) }
2344        };
2345
2346        let iter = self.bytes[self.error.valid_up_to()..].utf8_chunks();
2347
2348        for chunk in iter {
2349            res.push_str(chunk.valid());
2350            if !chunk.invalid().is_empty() {
2351                res.push_str(REPLACEMENT);
2352            }
2353        }
2354
2355        res
2356    }
2357
2358    /// Returns the bytes that were attempted to convert to a `String`.
2359    ///
2360    /// This method is carefully constructed to avoid allocation. It will
2361    /// consume the error, moving out the bytes, so that a copy of the bytes
2362    /// does not need to be made.
2363    ///
2364    /// # Examples
2365    ///
2366    /// ```
2367    /// // some invalid bytes, in a vector
2368    /// let bytes = vec![0, 159];
2369    ///
2370    /// let value = String::from_utf8(bytes);
2371    ///
2372    /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
2373    /// ```
2374    #[must_use = "`self` will be dropped if the result is not used"]
2375    #[stable(feature = "rust1", since = "1.0.0")]
2376    pub fn into_bytes(self) -> Vec<u8> {
2377        self.bytes
2378    }
2379
2380    /// Fetch a `Utf8Error` to get more details about the conversion failure.
2381    ///
2382    /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
2383    /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
2384    /// an analogue to `FromUtf8Error`. See its documentation for more details
2385    /// on using it.
2386    ///
2387    /// [`std::str`]: core::str "std::str"
2388    /// [`&str`]: prim@str "&str"
2389    ///
2390    /// # Examples
2391    ///
2392    /// ```
2393    /// // some invalid bytes, in a vector
2394    /// let bytes = vec![0, 159];
2395    ///
2396    /// let error = String::from_utf8(bytes).unwrap_err().utf8_error();
2397    ///
2398    /// // the first byte is invalid here
2399    /// assert_eq!(1, error.valid_up_to());
2400    /// ```
2401    #[must_use]
2402    #[stable(feature = "rust1", since = "1.0.0")]
2403    pub fn utf8_error(&self) -> Utf8Error {
2404        self.error
2405    }
2406}
2407
2408#[stable(feature = "rust1", since = "1.0.0")]
2409impl fmt::Display for FromUtf8Error {
2410    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2411        fmt::Display::fmt(&self.error, f)
2412    }
2413}
2414
2415#[stable(feature = "rust1", since = "1.0.0")]
2416impl fmt::Display for FromUtf16Error {
2417    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2418        match self.kind {
2419            FromUtf16ErrorKind::LoneSurrogate => "invalid utf-16: lone surrogate found",
2420            FromUtf16ErrorKind::OddBytes => "invalid utf-16: odd number of bytes",
2421        }
2422        .fmt(f)
2423    }
2424}
2425
2426#[stable(feature = "rust1", since = "1.0.0")]
2427impl Error for FromUtf8Error {}
2428
2429#[stable(feature = "rust1", since = "1.0.0")]
2430impl Error for FromUtf16Error {}
2431
2432#[cfg(not(no_global_oom_handling))]
2433#[stable(feature = "rust1", since = "1.0.0")]
2434impl Clone for String {
2435    fn clone(&self) -> Self {
2436        String { vec: self.vec.clone() }
2437    }
2438
2439    /// Clones the contents of `source` into `self`.
2440    ///
2441    /// This method is preferred over simply assigning `source.clone()` to `self`,
2442    /// as it avoids reallocation if possible.
2443    fn clone_from(&mut self, source: &Self) {
2444        self.vec.clone_from(&source.vec);
2445    }
2446}
2447
2448#[cfg(not(no_global_oom_handling))]
2449#[stable(feature = "rust1", since = "1.0.0")]
2450impl FromIterator<char> for String {
2451    fn from_iter<I: IntoIterator<Item = char>>(iter: I) -> String {
2452        FromCharIterSpec::to_string_spec(iter.into_iter())
2453    }
2454}
2455
2456#[cfg(not(no_global_oom_handling))]
2457trait FromCharIterSpec: Iterator<Item = char> {
2458    fn to_string_spec(self) -> String;
2459}
2460
2461#[cfg(not(no_global_oom_handling))]
2462impl<T> FromCharIterSpec for T
2463where
2464    T: Iterator<Item = char>,
2465{
2466    default fn to_string_spec(self) -> String {
2467        let mut buf = String::with_capacity(self.size_hint().0);
2468        buf.extend(self);
2469        buf
2470    }
2471}
2472
2473#[cfg(not(no_global_oom_handling))]
2474impl FromCharIterSpec for core::str::EscapeDefault<'_> {
2475    fn to_string_spec(self) -> String {
2476        // go through the ToString specialization
2477        self.to_string()
2478    }
2479}
2480
2481#[cfg(not(no_global_oom_handling))]
2482#[stable(feature = "string_from_iter_by_ref", since = "1.17.0")]
2483impl<'a> FromIterator<&'a char> for String {
2484    fn from_iter<I: IntoIterator<Item = &'a char>>(iter: I) -> String {
2485        let mut buf = String::new();
2486        buf.extend(iter);
2487        buf
2488    }
2489}
2490
2491#[cfg(not(no_global_oom_handling))]
2492#[stable(feature = "rust1", since = "1.0.0")]
2493impl<'a> FromIterator<&'a str> for String {
2494    fn from_iter<I: IntoIterator<Item = &'a str>>(iter: I) -> String {
2495        let mut buf = String::new();
2496        buf.extend(iter);
2497        buf
2498    }
2499}
2500
2501#[cfg(not(no_global_oom_handling))]
2502#[stable(feature = "extend_string", since = "1.4.0")]
2503impl FromIterator<String> for String {
2504    fn from_iter<I: IntoIterator<Item = String>>(iter: I) -> String {
2505        let mut iterator = iter.into_iter();
2506
2507        // Because we're iterating over `String`s, we can avoid at least
2508        // one allocation by getting the first string from the iterator
2509        // and appending to it all the subsequent strings.
2510        match iterator.next() {
2511            None => String::new(),
2512            Some(mut buf) => {
2513                buf.extend(iterator);
2514                buf
2515            }
2516        }
2517    }
2518}
2519
2520#[cfg(not(no_global_oom_handling))]
2521#[stable(feature = "box_str2", since = "1.45.0")]
2522impl<A: Allocator> FromIterator<Box<str, A>> for String {
2523    fn from_iter<I: IntoIterator<Item = Box<str, A>>>(iter: I) -> String {
2524        let mut buf = String::new();
2525        buf.extend(iter);
2526        buf
2527    }
2528}
2529
2530#[cfg(not(no_global_oom_handling))]
2531#[stable(feature = "herd_cows", since = "1.19.0")]
2532impl<'a> FromIterator<Cow<'a, str>> for String {
2533    fn from_iter<I: IntoIterator<Item = Cow<'a, str>>>(iter: I) -> String {
2534        let mut iterator = iter.into_iter();
2535
2536        // Because we're iterating over CoWs, we can (potentially) avoid at least
2537        // one allocation by getting the first item and appending to it all the
2538        // subsequent items.
2539        match iterator.next() {
2540            None => String::new(),
2541            Some(cow) => {
2542                let mut buf = cow.into_owned();
2543                buf.extend(iterator);
2544                buf
2545            }
2546        }
2547    }
2548}
2549
2550#[cfg(not(no_global_oom_handling))]
2551#[unstable(feature = "ascii_char", issue = "110998")]
2552impl FromIterator<core::ascii::Char> for String {
2553    fn from_iter<I: IntoIterator<Item = core::ascii::Char>>(iter: I) -> Self {
2554        let buf = iter.into_iter().map(core::ascii::Char::to_u8).collect();
2555        // SAFETY: `buf` is guaranteed to be valid UTF-8 because the `core::ascii::Char` type
2556        // only contains ASCII values (0x00-0x7F), which are valid UTF-8.
2557        unsafe { String::from_utf8_unchecked(buf) }
2558    }
2559}
2560
2561#[cfg(not(no_global_oom_handling))]
2562#[unstable(feature = "ascii_char", issue = "110998")]
2563impl<'a> FromIterator<&'a core::ascii::Char> for String {
2564    fn from_iter<I: IntoIterator<Item = &'a core::ascii::Char>>(iter: I) -> Self {
2565        let buf = iter.into_iter().copied().map(core::ascii::Char::to_u8).collect();
2566        // SAFETY: `buf` is guaranteed to be valid UTF-8 because the `core::ascii::Char` type
2567        // only contains ASCII values (0x00-0x7F), which are valid UTF-8.
2568        unsafe { String::from_utf8_unchecked(buf) }
2569    }
2570}
2571
2572#[cfg(not(no_global_oom_handling))]
2573#[stable(feature = "rust1", since = "1.0.0")]
2574impl Extend<char> for String {
2575    fn extend<I: IntoIterator<Item = char>>(&mut self, iter: I) {
2576        SpecExtendChars::spec_extend_into(iter, self);
2577    }
2578
2579    #[inline]
2580    fn extend_one(&mut self, c: char) {
2581        self.push(c);
2582    }
2583
2584    #[inline]
2585    fn extend_reserve(&mut self, additional: usize) {
2586        self.reserve(additional);
2587    }
2588}
2589
2590#[cfg(not(no_global_oom_handling))]
2591trait SpecExtendChars {
2592    fn spec_extend_into(self, s: &mut String);
2593}
2594
2595#[cfg(not(no_global_oom_handling))]
2596impl<T: IntoIterator<Item = char>> SpecExtendChars for T {
2597    default fn spec_extend_into(self, target: &mut String) {
2598        let iterator = self.into_iter();
2599        let (lower_bound, _) = iterator.size_hint();
2600        target.reserve(lower_bound);
2601        iterator.for_each(move |c| target.push(c));
2602    }
2603}
2604
2605#[cfg(not(no_global_oom_handling))]
2606impl SpecExtendChars for core::str::EscapeDefault<'_> {
2607    fn spec_extend_into(self, target: &mut String) {
2608        target.extend_from_escape_default(self);
2609    }
2610}
2611
2612#[cfg(not(no_global_oom_handling))]
2613#[stable(feature = "extend_ref", since = "1.2.0")]
2614impl<'a> Extend<&'a char> for String {
2615    fn extend<I: IntoIterator<Item = &'a char>>(&mut self, iter: I) {
2616        self.extend(iter.into_iter().cloned());
2617    }
2618
2619    #[inline]
2620    fn extend_one(&mut self, &c: &'a char) {
2621        self.push(c);
2622    }
2623
2624    #[inline]
2625    fn extend_reserve(&mut self, additional: usize) {
2626        self.reserve(additional);
2627    }
2628}
2629
2630#[cfg(not(no_global_oom_handling))]
2631#[stable(feature = "rust1", since = "1.0.0")]
2632impl<'a> Extend<&'a str> for String {
2633    fn extend<I: IntoIterator<Item = &'a str>>(&mut self, iter: I) {
2634        <I as SpecExtendStr>::spec_extend_into(iter, self)
2635    }
2636
2637    #[inline]
2638    fn extend_one(&mut self, s: &'a str) {
2639        self.push_str(s);
2640    }
2641}
2642
2643#[cfg(not(no_global_oom_handling))]
2644trait SpecExtendStr {
2645    fn spec_extend_into(self, s: &mut String);
2646}
2647
2648#[cfg(not(no_global_oom_handling))]
2649impl<'a, T: IntoIterator<Item = &'a str>> SpecExtendStr for T {
2650    default fn spec_extend_into(self, target: &mut String) {
2651        self.into_iter().for_each(move |s| target.push_str(s));
2652    }
2653}
2654
2655#[cfg(not(no_global_oom_handling))]
2656impl SpecExtendStr for [&str] {
2657    fn spec_extend_into(self, target: &mut String) {
2658        target.push_str_slice(&self);
2659    }
2660}
2661
2662#[cfg(not(no_global_oom_handling))]
2663impl<const N: usize> SpecExtendStr for [&str; N] {
2664    fn spec_extend_into(self, target: &mut String) {
2665        target.push_str_slice(&self[..]);
2666    }
2667}
2668
2669#[cfg(not(no_global_oom_handling))]
2670#[stable(feature = "box_str2", since = "1.45.0")]
2671impl<A: Allocator> Extend<Box<str, A>> for String {
2672    fn extend<I: IntoIterator<Item = Box<str, A>>>(&mut self, iter: I) {
2673        iter.into_iter().for_each(move |s| self.push_str(&s));
2674    }
2675}
2676
2677#[cfg(not(no_global_oom_handling))]
2678#[stable(feature = "extend_string", since = "1.4.0")]
2679impl Extend<String> for String {
2680    fn extend<I: IntoIterator<Item = String>>(&mut self, iter: I) {
2681        iter.into_iter().for_each(move |s| self.push_str(&s));
2682    }
2683
2684    #[inline]
2685    fn extend_one(&mut self, s: String) {
2686        self.push_str(&s);
2687    }
2688}
2689
2690#[cfg(not(no_global_oom_handling))]
2691#[stable(feature = "herd_cows", since = "1.19.0")]
2692impl<'a> Extend<Cow<'a, str>> for String {
2693    fn extend<I: IntoIterator<Item = Cow<'a, str>>>(&mut self, iter: I) {
2694        iter.into_iter().for_each(move |s| self.push_str(&s));
2695    }
2696
2697    #[inline]
2698    fn extend_one(&mut self, s: Cow<'a, str>) {
2699        self.push_str(&s);
2700    }
2701}
2702
2703#[cfg(not(no_global_oom_handling))]
2704#[unstable(feature = "ascii_char", issue = "110998")]
2705impl Extend<core::ascii::Char> for String {
2706    #[inline]
2707    fn extend<I: IntoIterator<Item = core::ascii::Char>>(&mut self, iter: I) {
2708        self.vec.extend(iter.into_iter().map(|c| c.to_u8()));
2709    }
2710
2711    #[inline]
2712    fn extend_one(&mut self, c: core::ascii::Char) {
2713        self.vec.push(c.to_u8());
2714    }
2715}
2716
2717#[cfg(not(no_global_oom_handling))]
2718#[unstable(feature = "ascii_char", issue = "110998")]
2719impl<'a> Extend<&'a core::ascii::Char> for String {
2720    #[inline]
2721    fn extend<I: IntoIterator<Item = &'a core::ascii::Char>>(&mut self, iter: I) {
2722        self.extend(iter.into_iter().cloned());
2723    }
2724
2725    #[inline]
2726    fn extend_one(&mut self, c: &'a core::ascii::Char) {
2727        self.vec.push(c.to_u8());
2728    }
2729}
2730
2731/// A convenience impl that delegates to the impl for `&str`.
2732///
2733/// # Examples
2734///
2735/// ```
2736/// assert_eq!(String::from("Hello world").find("world"), Some(6));
2737/// ```
2738#[unstable(
2739    feature = "pattern",
2740    reason = "API not fully fleshed out and ready to be stabilized",
2741    issue = "27721"
2742)]
2743impl<'b> Pattern for &'b String {
2744    type Searcher<'a> = <&'b str as Pattern>::Searcher<'a>;
2745
2746    fn into_searcher(self, haystack: &str) -> <&'b str as Pattern>::Searcher<'_> {
2747        self[..].into_searcher(haystack)
2748    }
2749
2750    #[inline]
2751    fn is_contained_in(self, haystack: &str) -> bool {
2752        self[..].is_contained_in(haystack)
2753    }
2754
2755    #[inline]
2756    fn is_prefix_of(self, haystack: &str) -> bool {
2757        self[..].is_prefix_of(haystack)
2758    }
2759
2760    #[inline]
2761    fn strip_prefix_of(self, haystack: &str) -> Option<&str> {
2762        self[..].strip_prefix_of(haystack)
2763    }
2764
2765    #[inline]
2766    fn is_suffix_of<'a>(self, haystack: &'a str) -> bool
2767    where
2768        Self::Searcher<'a>: core::str::pattern::ReverseSearcher<'a>,
2769    {
2770        self[..].is_suffix_of(haystack)
2771    }
2772
2773    #[inline]
2774    fn strip_suffix_of<'a>(self, haystack: &'a str) -> Option<&'a str>
2775    where
2776        Self::Searcher<'a>: core::str::pattern::ReverseSearcher<'a>,
2777    {
2778        self[..].strip_suffix_of(haystack)
2779    }
2780
2781    #[inline]
2782    fn as_utf8_pattern(&self) -> Option<Utf8Pattern<'_>> {
2783        Some(Utf8Pattern::StringPattern(self.as_str()))
2784    }
2785}
2786
2787macro_rules! impl_eq {
2788    ($lhs:ty, $rhs: ty) => {
2789        #[stable(feature = "rust1", since = "1.0.0")]
2790        impl PartialEq<$rhs> for $lhs {
2791            #[inline]
2792            fn eq(&self, other: &$rhs) -> bool {
2793                PartialEq::eq(&self[..], &other[..])
2794            }
2795            #[inline]
2796            fn ne(&self, other: &$rhs) -> bool {
2797                PartialEq::ne(&self[..], &other[..])
2798            }
2799        }
2800
2801        #[stable(feature = "rust1", since = "1.0.0")]
2802        impl PartialEq<$lhs> for $rhs {
2803            #[inline]
2804            fn eq(&self, other: &$lhs) -> bool {
2805                PartialEq::eq(&self[..], &other[..])
2806            }
2807            #[inline]
2808            fn ne(&self, other: &$lhs) -> bool {
2809                PartialEq::ne(&self[..], &other[..])
2810            }
2811        }
2812    };
2813}
2814
2815impl_eq! { String, str }
2816impl_eq! { String, &str }
2817#[cfg(not(no_global_oom_handling))]
2818impl_eq! { Cow<'_, str>, str }
2819#[cfg(not(no_global_oom_handling))]
2820impl_eq! { Cow<'_, str>, &'_ str }
2821#[cfg(not(no_global_oom_handling))]
2822impl_eq! { Cow<'_, str>, String }
2823
2824#[stable(feature = "rust1", since = "1.0.0")]
2825#[rustc_const_unstable(feature = "const_default", issue = "143894")]
2826const impl Default for String {
2827    /// Creates an empty `String`.
2828    #[inline]
2829    fn default() -> String {
2830        String::new()
2831    }
2832}
2833
2834#[stable(feature = "rust1", since = "1.0.0")]
2835impl fmt::Display for String {
2836    #[inline]
2837    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2838        fmt::Display::fmt(&**self, f)
2839    }
2840}
2841
2842#[stable(feature = "rust1", since = "1.0.0")]
2843impl fmt::Debug for String {
2844    #[inline]
2845    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2846        fmt::Debug::fmt(&**self, f)
2847    }
2848}
2849
2850#[stable(feature = "rust1", since = "1.0.0")]
2851impl hash::Hash for String {
2852    #[inline]
2853    fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
2854        (**self).hash(hasher)
2855    }
2856}
2857
2858/// Implements the `+` operator for concatenating two strings.
2859///
2860/// This consumes the `String` on the left-hand side and re-uses its buffer (growing it if
2861/// necessary). This is done to avoid allocating a new `String` and copying the entire contents on
2862/// every operation, which would lead to *O*(*n*^2) running time when building an *n*-byte string by
2863/// repeated concatenation.
2864///
2865/// The string on the right-hand side is only borrowed; its contents are copied into the returned
2866/// `String`.
2867///
2868/// # Examples
2869///
2870/// Concatenating two `String`s takes the first by value and borrows the second:
2871///
2872/// ```
2873/// let a = String::from("hello");
2874/// let b = String::from(" world");
2875/// let c = a + &b;
2876/// // `a` is moved and can no longer be used here.
2877/// ```
2878///
2879/// If you want to keep using the first `String`, you can clone it and append to the clone instead:
2880///
2881/// ```
2882/// let a = String::from("hello");
2883/// let b = String::from(" world");
2884/// let c = a.clone() + &b;
2885/// // `a` is still valid here.
2886/// ```
2887///
2888/// Concatenating `&str` slices can be done by converting the first to a `String`:
2889///
2890/// ```
2891/// let a = "hello";
2892/// let b = " world";
2893/// let c = a.to_string() + b;
2894/// ```
2895#[cfg(not(no_global_oom_handling))]
2896#[stable(feature = "rust1", since = "1.0.0")]
2897impl Add<&str> for String {
2898    type Output = String;
2899
2900    #[inline]
2901    fn add(mut self, other: &str) -> String {
2902        self.push_str(other);
2903        self
2904    }
2905}
2906
2907/// Implements the `+=` operator for appending to a `String`.
2908///
2909/// This has the same behavior as the [`push_str`][String::push_str] method.
2910#[cfg(not(no_global_oom_handling))]
2911#[stable(feature = "stringaddassign", since = "1.12.0")]
2912impl AddAssign<&str> for String {
2913    #[inline]
2914    fn add_assign(&mut self, other: &str) {
2915        self.push_str(other);
2916    }
2917}
2918
2919#[stable(feature = "rust1", since = "1.0.0")]
2920impl<I> ops::Index<I> for String
2921where
2922    I: slice::SliceIndex<str>,
2923{
2924    type Output = I::Output;
2925
2926    #[inline]
2927    fn index(&self, index: I) -> &I::Output {
2928        index.index(self.as_str())
2929    }
2930}
2931
2932#[stable(feature = "rust1", since = "1.0.0")]
2933impl<I> ops::IndexMut<I> for String
2934where
2935    I: slice::SliceIndex<str>,
2936{
2937    #[inline]
2938    fn index_mut(&mut self, index: I) -> &mut I::Output {
2939        index.index_mut(self.as_mut_str())
2940    }
2941}
2942
2943#[stable(feature = "rust1", since = "1.0.0")]
2944impl ops::Deref for String {
2945    type Target = str;
2946
2947    #[inline]
2948    fn deref(&self) -> &str {
2949        self.as_str()
2950    }
2951}
2952
2953#[unstable(feature = "deref_pure_trait", issue = "87121")]
2954unsafe impl ops::DerefPure for String {}
2955
2956#[stable(feature = "derefmut_for_string", since = "1.3.0")]
2957impl ops::DerefMut for String {
2958    #[inline]
2959    fn deref_mut(&mut self) -> &mut str {
2960        self.as_mut_str()
2961    }
2962}
2963
2964/// A type alias for [`!`].
2965///
2966/// This alias exists for backwards compatibility, and may be eventually deprecated.
2967#[stable(feature = "str_parse_error", since = "1.5.0")]
2968pub type ParseError = !;
2969
2970#[cfg(not(no_global_oom_handling))]
2971#[stable(feature = "rust1", since = "1.0.0")]
2972impl FromStr for String {
2973    type Err = !;
2974    #[inline]
2975    fn from_str(s: &str) -> Result<String, !> {
2976        Ok(String::from(s))
2977    }
2978}
2979
2980/// A trait for converting a value to a `String`.
2981///
2982/// This trait is automatically implemented for any type which implements the
2983/// [`Display`] trait. As such, `ToString` shouldn't be implemented directly:
2984/// [`Display`] should be implemented instead, and you get the `ToString`
2985/// implementation for free.
2986///
2987/// [`Display`]: fmt::Display
2988#[rustc_diagnostic_item = "ToString"]
2989#[stable(feature = "rust1", since = "1.0.0")]
2990pub trait ToString {
2991    /// Converts the given value to a `String`.
2992    ///
2993    /// # Examples
2994    ///
2995    /// ```
2996    /// let i = 5;
2997    /// let five = String::from("5");
2998    ///
2999    /// assert_eq!(five, i.to_string());
3000    /// ```
3001    #[rustc_conversion_suggestion]
3002    #[stable(feature = "rust1", since = "1.0.0")]
3003    #[rustc_diagnostic_item = "to_string_method"]
3004    fn to_string(&self) -> String;
3005}
3006
3007/// # Panics
3008///
3009/// In this implementation, the `to_string` method panics
3010/// if the `Display` implementation returns an error.
3011/// This indicates an incorrect `Display` implementation
3012/// since `fmt::Write for String` never returns an error itself.
3013#[cfg(not(no_global_oom_handling))]
3014#[stable(feature = "rust1", since = "1.0.0")]
3015impl<T: fmt::Display + ?Sized> ToString for T {
3016    #[inline]
3017    fn to_string(&self) -> String {
3018        <Self as SpecToString>::spec_to_string(self)
3019    }
3020}
3021
3022#[cfg(not(no_global_oom_handling))]
3023trait SpecToString {
3024    fn spec_to_string(&self) -> String;
3025}
3026
3027#[cfg(not(no_global_oom_handling))]
3028impl<T: fmt::Display + ?Sized> SpecToString for T {
3029    // A common guideline is to not inline generic functions. However,
3030    // removing `#[inline]` from this method causes non-negligible regressions.
3031    // See <https://github.com/rust-lang/rust/pull/74852>, the last attempt
3032    // to try to remove it.
3033    #[inline]
3034    default fn spec_to_string(&self) -> String {
3035        let mut buf = String::new();
3036        let mut formatter =
3037            core::fmt::Formatter::new(&mut buf, core::fmt::FormattingOptions::new());
3038        // Bypass format_args!() to avoid write_str with zero-length strs
3039        fmt::Display::fmt(self, &mut formatter)
3040            .expect("a Display implementation returned an error unexpectedly");
3041        buf
3042    }
3043}
3044
3045#[cfg(not(no_global_oom_handling))]
3046impl SpecToString for core::ascii::Char {
3047    #[inline]
3048    fn spec_to_string(&self) -> String {
3049        self.as_str().to_owned()
3050    }
3051}
3052
3053#[cfg(not(no_global_oom_handling))]
3054impl SpecToString for char {
3055    #[inline]
3056    fn spec_to_string(&self) -> String {
3057        String::from(self.encode_utf8(&mut [0; char::MAX_LEN_UTF8]))
3058    }
3059}
3060
3061#[cfg(not(no_global_oom_handling))]
3062impl SpecToString for bool {
3063    #[inline]
3064    fn spec_to_string(&self) -> String {
3065        String::from(if *self { "true" } else { "false" })
3066    }
3067}
3068
3069macro_rules! impl_to_string {
3070    ($($signed:ident, $unsigned:ident,)*) => {
3071        $(
3072        #[cfg(not(no_global_oom_handling))]
3073        #[cfg(not(feature = "optimize_for_size"))]
3074        impl SpecToString for $signed {
3075            #[inline]
3076            fn spec_to_string(&self) -> String {
3077                const SIZE: usize = $signed::MAX.ilog10() as usize + 1;
3078                let mut buf = [core::mem::MaybeUninit::<u8>::uninit(); SIZE];
3079                // Only difference between signed and unsigned are these 8 lines.
3080                let mut out;
3081                if *self < 0 {
3082                    out = String::with_capacity(SIZE + 1);
3083                    out.push('-');
3084                } else {
3085                    out = String::with_capacity(SIZE);
3086                }
3087
3088                // SAFETY: `buf` is always big enough to contain all the digits.
3089                unsafe { out.push_str(self.unsigned_abs()._fmt(&mut buf)); }
3090                out
3091            }
3092        }
3093        #[cfg(not(no_global_oom_handling))]
3094        #[cfg(not(feature = "optimize_for_size"))]
3095        impl SpecToString for $unsigned {
3096            #[inline]
3097            fn spec_to_string(&self) -> String {
3098                const SIZE: usize = $unsigned::MAX.ilog10() as usize + 1;
3099                let mut buf = [core::mem::MaybeUninit::<u8>::uninit(); SIZE];
3100
3101                // SAFETY: `buf` is always big enough to contain all the digits.
3102                unsafe { self._fmt(&mut buf).to_string() }
3103            }
3104        }
3105        )*
3106    }
3107}
3108
3109impl_to_string! {
3110    i8, u8,
3111    i16, u16,
3112    i32, u32,
3113    i64, u64,
3114    isize, usize,
3115    i128, u128,
3116}
3117
3118#[cfg(not(no_global_oom_handling))]
3119#[cfg(feature = "optimize_for_size")]
3120impl SpecToString for u8 {
3121    #[inline]
3122    fn spec_to_string(&self) -> String {
3123        let mut buf = String::with_capacity(3);
3124        let mut n = *self;
3125        if n >= 10 {
3126            if n >= 100 {
3127                buf.push((b'0' + n / 100) as char);
3128                n %= 100;
3129            }
3130            buf.push((b'0' + n / 10) as char);
3131            n %= 10;
3132        }
3133        buf.push((b'0' + n) as char);
3134        buf
3135    }
3136}
3137
3138#[cfg(not(no_global_oom_handling))]
3139#[cfg(feature = "optimize_for_size")]
3140impl SpecToString for i8 {
3141    #[inline]
3142    fn spec_to_string(&self) -> String {
3143        let mut buf = String::with_capacity(4);
3144        if self.is_negative() {
3145            buf.push('-');
3146        }
3147        let mut n = self.unsigned_abs();
3148        if n >= 10 {
3149            if n >= 100 {
3150                buf.push('1');
3151                n -= 100;
3152            }
3153            buf.push((b'0' + n / 10) as char);
3154            n %= 10;
3155        }
3156        buf.push((b'0' + n) as char);
3157        buf
3158    }
3159}
3160
3161#[cfg(not(no_global_oom_handling))]
3162macro_rules! to_string_str {
3163    {$($type:ty,)*} => {
3164        $(
3165            impl SpecToString for $type {
3166                #[inline]
3167                fn spec_to_string(&self) -> String {
3168                    let s: &str = self;
3169                    String::from(s)
3170                }
3171            }
3172        )*
3173    };
3174}
3175
3176#[cfg(not(no_global_oom_handling))]
3177to_string_str! {
3178    Cow<'_, str>,
3179    String,
3180    // Generic/generated code can sometimes have multiple, nested references
3181    // for strings, including `&&&str`s that would never be written
3182    // by hand.
3183    &&&&&&&&&&&&str,
3184    &&&&&&&&&&&str,
3185    &&&&&&&&&&str,
3186    &&&&&&&&&str,
3187    &&&&&&&&str,
3188    &&&&&&&str,
3189    &&&&&&str,
3190    &&&&&str,
3191    &&&&str,
3192    &&&str,
3193    &&str,
3194    &str,
3195    str,
3196}
3197
3198#[cfg(not(no_global_oom_handling))]
3199impl SpecToString for fmt::Arguments<'_> {
3200    #[inline]
3201    fn spec_to_string(&self) -> String {
3202        crate::fmt::format(*self)
3203    }
3204}
3205
3206#[cfg(not(no_global_oom_handling))]
3207impl SpecToString for core::str::EscapeDefault<'_> {
3208    fn spec_to_string(&self) -> String {
3209        let mut s = String::new();
3210        s.extend_from_escape_default(self.clone());
3211        s
3212    }
3213}
3214
3215#[cfg(not(no_global_oom_handling))]
3216impl String {
3217    #[inline]
3218    fn extend_from_escape_default(&mut self, escaper: core::str::EscapeDefault<'_>) {
3219        let (front, middle, tail) = escaper.into_parts();
3220        let lengths = front.as_ref().map_or_default(|f| f.size_hint().0)
3221            + middle.as_ref().map_or_default(|m| m.size_hint().0)
3222            + tail.as_ref().map_or_default(|t| t.size_hint().0);
3223        self.reserve(lengths);
3224
3225        if let Some(front) = front {
3226            self.extend(front);
3227        }
3228        if let Some(middle) = middle {
3229            /// Ensures a spare capacity of N bytes and then passes that as MaybeUninit
3230            /// slice to a closure that returns the bytes written, then
3231            /// updates the length.
3232            ///
3233            /// # Safety:
3234            ///
3235            /// The caller must initialize the number of bytes returned by the closure.
3236            #[inline]
3237            unsafe fn with_spare<const N: usize, T>(
3238                bytes: &mut Vec<u8>,
3239                then: impl FnOnce(&mut [MaybeUninit<T>; N]) -> usize,
3240            ) {
3241                const {
3242                    assert!(core::mem::size_of::<T>() == 1);
3243                }
3244                bytes.reserve(N);
3245                let old_len = bytes.len();
3246                // SAFETY: We reserved enough space for the requested number of bytes.
3247                unsafe {
3248                    let spare: &mut [MaybeUninit<T>; N] = bytes
3249                        .spare_capacity_mut()
3250                        .as_mut_ptr()
3251                        .cast::<T>()
3252                        .cast_uninit()
3253                        .cast_array::<N>()
3254                        .as_mut_unchecked();
3255                    let written = then(spare);
3256                    bytes.set_len(old_len + written);
3257                }
3258            }
3259
3260            for c in middle {
3261                match c {
3262                    '\'' | '\"' | '\\' => {
3263                        self.push('\\');
3264                        self.push(c);
3265                    }
3266                    '\x20'..='\x7e' => self.push(c),
3267                    '\t' => {
3268                        self.push('\\');
3269                        self.push('t');
3270                    }
3271                    '\r' => {
3272                        self.push('\\');
3273                        self.push('r');
3274                    }
3275                    '\n' => {
3276                        self.push('\\');
3277                        self.push('n');
3278                    }
3279                    c => {
3280                        // SAFETY: We only let the function write ascii chars, so it remains valid utf8.
3281                        // and it returns the number of bytes written, so so with_spare ensures the rest for us.
3282                        unsafe {
3283                            with_spare::<10, ascii::Char>(self.as_mut_vec(), |spare| {
3284                                escape_unicode_into(spare, c)
3285                            });
3286                        }
3287                    }
3288                }
3289            }
3290        }
3291
3292        if let Some(tail) = tail {
3293            self.extend(tail);
3294        }
3295    }
3296}
3297
3298#[cfg(not(no_global_oom_handling))]
3299#[inline]
3300// adapted from core::escape::escape_unicode, but it's left-aligned instead of right-aligned.
3301fn escape_unicode_into(output: &mut [MaybeUninit<ascii::Char>; 10], c: char) -> usize {
3302    const HEX_DIGITS: [ascii::Char; 16] = *b"0123456789abcdef".as_ascii().unwrap();
3303
3304    let c = c as u32;
3305    // OR-ing `1` ensures that for `c == 0` the code computes that
3306    // one digit should be printed.
3307    let prefix_skip = (c | 1).leading_zeros() as usize / 4 - 2;
3308
3309    // Always write all digits, but for shorter representations the unused
3310    // digits get overwritten by later writes.
3311    output[3usize.saturating_sub(prefix_skip)].write(HEX_DIGITS[((c >> 20) & 15) as usize]);
3312    output[4usize.saturating_sub(prefix_skip)].write(HEX_DIGITS[((c >> 16) & 15) as usize]);
3313    output[5usize.saturating_sub(prefix_skip)].write(HEX_DIGITS[((c >> 12) & 15) as usize]);
3314    output[6usize.saturating_sub(prefix_skip)].write(HEX_DIGITS[((c >> 8) & 15) as usize]);
3315    output[7usize.saturating_sub(prefix_skip)].write(HEX_DIGITS[((c >> 4) & 15) as usize]);
3316    output[8usize.saturating_sub(prefix_skip)].write(HEX_DIGITS[(c & 15) as usize]);
3317
3318    output[0].write(ascii::Char::ReverseSolidus);
3319    output[1].write(ascii::Char::SmallU);
3320    output[2].write(ascii::Char::LeftCurlyBracket);
3321    output[9 - prefix_skip].write(ascii::Char::RightCurlyBracket);
3322
3323    10 - prefix_skip
3324}
3325
3326#[stable(feature = "rust1", since = "1.0.0")]
3327impl AsRef<str> for String {
3328    #[inline]
3329    fn as_ref(&self) -> &str {
3330        self
3331    }
3332}
3333
3334#[stable(feature = "string_as_mut", since = "1.43.0")]
3335impl AsMut<str> for String {
3336    #[inline]
3337    fn as_mut(&mut self) -> &mut str {
3338        self
3339    }
3340}
3341
3342#[stable(feature = "rust1", since = "1.0.0")]
3343impl AsRef<[u8]> for String {
3344    #[inline]
3345    fn as_ref(&self) -> &[u8] {
3346        self.as_bytes()
3347    }
3348}
3349
3350#[cfg(not(no_global_oom_handling))]
3351#[stable(feature = "rust1", since = "1.0.0")]
3352impl From<&str> for String {
3353    /// Converts a `&str` into a [`String`].
3354    ///
3355    /// The result is allocated on the heap.
3356    #[inline]
3357    fn from(s: &str) -> String {
3358        s.to_owned()
3359    }
3360}
3361
3362#[cfg(not(no_global_oom_handling))]
3363#[stable(feature = "from_mut_str_for_string", since = "1.44.0")]
3364impl From<&mut str> for String {
3365    /// Converts a `&mut str` into a [`String`].
3366    ///
3367    /// The result is allocated on the heap.
3368    #[inline]
3369    fn from(s: &mut str) -> String {
3370        s.to_owned()
3371    }
3372}
3373
3374#[cfg(not(no_global_oom_handling))]
3375#[stable(feature = "from_ref_string", since = "1.35.0")]
3376impl From<&String> for String {
3377    /// Converts a `&String` into a [`String`].
3378    ///
3379    /// This clones `s` and returns the clone.
3380    #[inline]
3381    fn from(s: &String) -> String {
3382        s.clone()
3383    }
3384}
3385
3386// note: test pulls in std, which causes errors here
3387#[stable(feature = "string_from_box", since = "1.18.0")]
3388impl From<Box<str>> for String {
3389    /// Converts the given boxed `str` slice to a [`String`].
3390    /// It is notable that the `str` slice is owned.
3391    ///
3392    /// # Examples
3393    ///
3394    /// ```
3395    /// let s1: String = String::from("hello world");
3396    /// let s2: Box<str> = s1.into_boxed_str();
3397    /// let s3: String = String::from(s2);
3398    ///
3399    /// assert_eq!("hello world", s3)
3400    /// ```
3401    fn from(s: Box<str>) -> String {
3402        s.into_string()
3403    }
3404}
3405
3406#[cfg(not(no_global_oom_handling))]
3407#[stable(feature = "box_from_str", since = "1.20.0")]
3408impl From<String> for Box<str> {
3409    /// Converts the given [`String`] to a boxed `str` slice that is owned.
3410    ///
3411    /// # Examples
3412    ///
3413    /// ```
3414    /// let s1: String = String::from("hello world");
3415    /// let s2: Box<str> = Box::from(s1);
3416    /// let s3: String = String::from(s2);
3417    ///
3418    /// assert_eq!("hello world", s3)
3419    /// ```
3420    fn from(s: String) -> Box<str> {
3421        s.into_boxed_str()
3422    }
3423}
3424
3425#[cfg(not(no_global_oom_handling))]
3426#[stable(feature = "string_from_cow_str", since = "1.14.0")]
3427impl<'a> From<Cow<'a, str>> for String {
3428    /// Converts a clone-on-write string to an owned
3429    /// instance of [`String`].
3430    ///
3431    /// This extracts the owned string,
3432    /// clones the string if it is not already owned.
3433    ///
3434    /// # Example
3435    ///
3436    /// ```
3437    /// # use std::borrow::Cow;
3438    /// // If the string is not owned...
3439    /// let cow: Cow<'_, str> = Cow::Borrowed("eggplant");
3440    /// // It will allocate on the heap and copy the string.
3441    /// let owned: String = String::from(cow);
3442    /// assert_eq!(&owned[..], "eggplant");
3443    /// ```
3444    fn from(s: Cow<'a, str>) -> String {
3445        s.into_owned()
3446    }
3447}
3448
3449#[cfg(not(no_global_oom_handling))]
3450#[stable(feature = "rust1", since = "1.0.0")]
3451impl<'a> From<&'a str> for Cow<'a, str> {
3452    /// Converts a string slice into a [`Borrowed`] variant.
3453    /// No heap allocation is performed, and the string
3454    /// is not copied.
3455    ///
3456    /// # Example
3457    ///
3458    /// ```
3459    /// # use std::borrow::Cow;
3460    /// assert_eq!(Cow::from("eggplant"), Cow::Borrowed("eggplant"));
3461    /// ```
3462    ///
3463    /// [`Borrowed`]: crate::borrow::Cow::Borrowed "borrow::Cow::Borrowed"
3464    #[inline]
3465    fn from(s: &'a str) -> Cow<'a, str> {
3466        Cow::Borrowed(s)
3467    }
3468}
3469
3470#[cfg(not(no_global_oom_handling))]
3471#[stable(feature = "rust1", since = "1.0.0")]
3472impl<'a> From<String> for Cow<'a, str> {
3473    /// Converts a [`String`] into an [`Owned`] variant.
3474    /// No heap allocation is performed, and the string
3475    /// is not copied.
3476    ///
3477    /// # Example
3478    ///
3479    /// ```
3480    /// # use std::borrow::Cow;
3481    /// let s = "eggplant".to_string();
3482    /// let s2 = "eggplant".to_string();
3483    /// assert_eq!(Cow::from(s), Cow::<'static, str>::Owned(s2));
3484    /// ```
3485    ///
3486    /// [`Owned`]: crate::borrow::Cow::Owned "borrow::Cow::Owned"
3487    #[inline]
3488    fn from(s: String) -> Cow<'a, str> {
3489        Cow::Owned(s)
3490    }
3491}
3492
3493#[cfg(not(no_global_oom_handling))]
3494#[stable(feature = "cow_from_string_ref", since = "1.28.0")]
3495impl<'a> From<&'a String> for Cow<'a, str> {
3496    /// Converts a [`String`] reference into a [`Borrowed`] variant.
3497    /// No heap allocation is performed, and the string
3498    /// is not copied.
3499    ///
3500    /// # Example
3501    ///
3502    /// ```
3503    /// # use std::borrow::Cow;
3504    /// let s = "eggplant".to_string();
3505    /// assert_eq!(Cow::from(&s), Cow::Borrowed("eggplant"));
3506    /// ```
3507    ///
3508    /// [`Borrowed`]: crate::borrow::Cow::Borrowed "borrow::Cow::Borrowed"
3509    #[inline]
3510    fn from(s: &'a String) -> Cow<'a, str> {
3511        Cow::Borrowed(s.as_str())
3512    }
3513}
3514
3515#[cfg(not(no_global_oom_handling))]
3516#[stable(feature = "cow_str_from_iter", since = "1.12.0")]
3517impl<'a> FromIterator<char> for Cow<'a, str> {
3518    fn from_iter<I: IntoIterator<Item = char>>(it: I) -> Cow<'a, str> {
3519        Cow::Owned(FromIterator::from_iter(it))
3520    }
3521}
3522
3523#[cfg(not(no_global_oom_handling))]
3524#[stable(feature = "cow_str_from_iter", since = "1.12.0")]
3525impl<'a, 'b> FromIterator<&'b str> for Cow<'a, str> {
3526    fn from_iter<I: IntoIterator<Item = &'b str>>(it: I) -> Cow<'a, str> {
3527        Cow::Owned(FromIterator::from_iter(it))
3528    }
3529}
3530
3531#[cfg(not(no_global_oom_handling))]
3532#[stable(feature = "cow_str_from_iter", since = "1.12.0")]
3533impl<'a> FromIterator<String> for Cow<'a, str> {
3534    fn from_iter<I: IntoIterator<Item = String>>(it: I) -> Cow<'a, str> {
3535        Cow::Owned(FromIterator::from_iter(it))
3536    }
3537}
3538
3539#[cfg(not(no_global_oom_handling))]
3540#[unstable(feature = "ascii_char", issue = "110998")]
3541impl<'a> FromIterator<core::ascii::Char> for Cow<'a, str> {
3542    fn from_iter<I: IntoIterator<Item = core::ascii::Char>>(it: I) -> Self {
3543        Cow::Owned(FromIterator::from_iter(it))
3544    }
3545}
3546
3547#[stable(feature = "from_string_for_vec_u8", since = "1.14.0")]
3548impl From<String> for Vec<u8> {
3549    /// Converts the given [`String`] to a vector [`Vec`] that holds values of type [`u8`].
3550    ///
3551    /// # Examples
3552    ///
3553    /// ```
3554    /// let s1 = String::from("hello world");
3555    /// let v1 = Vec::from(s1);
3556    ///
3557    /// for b in v1 {
3558    ///     println!("{b}");
3559    /// }
3560    /// ```
3561    fn from(string: String) -> Vec<u8> {
3562        string.into_bytes()
3563    }
3564}
3565
3566#[stable(feature = "try_from_vec_u8_for_string", since = "1.87.0")]
3567impl TryFrom<Vec<u8>> for String {
3568    type Error = FromUtf8Error;
3569    /// Converts the given [`Vec<u8>`] into a  [`String`] if it contains valid UTF-8 data.
3570    ///
3571    /// # Examples
3572    ///
3573    /// ```
3574    /// let s1 = b"hello world".to_vec();
3575    /// let v1 = String::try_from(s1).unwrap();
3576    /// assert_eq!(v1, "hello world");
3577    ///
3578    /// ```
3579    fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
3580        Self::from_utf8(bytes)
3581    }
3582}
3583
3584/// Note that all methods of this trait append to the `String`'s existing
3585/// contents; they never truncate or replace what is already there. In
3586/// particular, [`fmt::Write::write_str`] uses [`push_str`][String::push_str]
3587/// and [`fmt::Write::write_char`] uses [`push`][String::push].
3588#[cfg(not(no_global_oom_handling))]
3589#[stable(feature = "rust1", since = "1.0.0")]
3590impl fmt::Write for String {
3591    #[inline]
3592    fn write_str(&mut self, s: &str) -> fmt::Result {
3593        self.push_str(s);
3594        Ok(())
3595    }
3596
3597    #[inline]
3598    fn write_char(&mut self, c: char) -> fmt::Result {
3599        self.push(c);
3600        Ok(())
3601    }
3602}
3603
3604/// An iterator over the [`char`]s of a string.
3605///
3606/// This struct is created by the [`into_chars`] method on [`String`].
3607/// See its documentation for more.
3608///
3609/// [`char`]: prim@char
3610/// [`into_chars`]: String::into_chars
3611#[cfg_attr(not(no_global_oom_handling), derive(Clone))]
3612#[must_use = "iterators are lazy and do nothing unless consumed"]
3613#[stable(feature = "string_into_chars", since = "CURRENT_RUSTC_VERSION")]
3614pub struct IntoChars {
3615    bytes: vec::IntoIter<u8>,
3616}
3617
3618#[stable(feature = "string_into_chars", since = "CURRENT_RUSTC_VERSION")]
3619impl fmt::Debug for IntoChars {
3620    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3621        f.debug_tuple("IntoChars").field(&self.as_str()).finish()
3622    }
3623}
3624
3625impl IntoChars {
3626    /// Views the underlying data as a subslice of the original data.
3627    ///
3628    /// # Examples
3629    ///
3630    /// ```
3631    /// let mut chars = String::from("abc").into_chars();
3632    ///
3633    /// assert_eq!(chars.as_str(), "abc");
3634    /// chars.next();
3635    /// assert_eq!(chars.as_str(), "bc");
3636    /// chars.next();
3637    /// chars.next();
3638    /// assert_eq!(chars.as_str(), "");
3639    /// ```
3640    #[stable(feature = "string_into_chars", since = "CURRENT_RUSTC_VERSION")]
3641    #[must_use]
3642    #[inline]
3643    pub fn as_str(&self) -> &str {
3644        // SAFETY: `bytes` is a valid UTF-8 string.
3645        unsafe { str::from_utf8_unchecked(self.bytes.as_slice()) }
3646    }
3647
3648    /// Consumes the `IntoChars`, returning the remaining string.
3649    ///
3650    /// # Examples
3651    ///
3652    /// ```
3653    /// let chars = String::from("abc").into_chars();
3654    /// assert_eq!(chars.into_string(), "abc");
3655    ///
3656    /// let mut chars = String::from("def").into_chars();
3657    /// chars.next();
3658    /// assert_eq!(chars.into_string(), "ef");
3659    /// ```
3660    #[cfg(not(no_global_oom_handling))]
3661    #[stable(feature = "string_into_chars", since = "CURRENT_RUSTC_VERSION")]
3662    #[inline]
3663    pub fn into_string(self) -> String {
3664        // SAFETY: `bytes` are kept in UTF-8 form, only removing whole `char`s at a time.
3665        unsafe { String::from_utf8_unchecked(self.bytes.collect()) }
3666    }
3667
3668    #[inline]
3669    fn iter(&self) -> CharIndices<'_> {
3670        self.as_str().char_indices()
3671    }
3672}
3673
3674#[stable(feature = "string_into_chars", since = "CURRENT_RUSTC_VERSION")]
3675impl Iterator for IntoChars {
3676    type Item = char;
3677
3678    #[inline]
3679    fn next(&mut self) -> Option<char> {
3680        let mut iter = self.iter();
3681        match iter.next() {
3682            None => None,
3683            Some((_, ch)) => {
3684                let offset = iter.offset();
3685                // `offset` is a valid index.
3686                let _ = self.bytes.advance_by(offset);
3687                Some(ch)
3688            }
3689        }
3690    }
3691
3692    #[inline]
3693    fn count(self) -> usize {
3694        self.iter().count()
3695    }
3696
3697    #[inline]
3698    fn size_hint(&self) -> (usize, Option<usize>) {
3699        self.iter().size_hint()
3700    }
3701
3702    #[inline]
3703    fn last(mut self) -> Option<char> {
3704        self.next_back()
3705    }
3706}
3707
3708#[stable(feature = "string_into_chars", since = "CURRENT_RUSTC_VERSION")]
3709impl DoubleEndedIterator for IntoChars {
3710    #[inline]
3711    fn next_back(&mut self) -> Option<char> {
3712        let len = self.as_str().len();
3713        let mut iter = self.iter();
3714        match iter.next_back() {
3715            None => None,
3716            Some((idx, ch)) => {
3717                // `idx` is a valid index.
3718                let _ = self.bytes.advance_back_by(len - idx);
3719                Some(ch)
3720            }
3721        }
3722    }
3723}
3724
3725#[stable(feature = "string_into_chars", since = "CURRENT_RUSTC_VERSION")]
3726impl FusedIterator for IntoChars {}
3727
3728/// A draining iterator for `String`.
3729///
3730/// This struct is created by the [`drain`] method on [`String`]. See its
3731/// documentation for more.
3732///
3733/// [`drain`]: String::drain
3734#[stable(feature = "drain", since = "1.6.0")]
3735pub struct Drain<'a> {
3736    /// Will be used as &'a mut String in the destructor
3737    string: *mut String,
3738    /// Start of part to remove
3739    start: usize,
3740    /// End of part to remove
3741    end: usize,
3742    /// Current remaining range to remove
3743    iter: Chars<'a>,
3744}
3745
3746#[stable(feature = "collection_debug", since = "1.17.0")]
3747impl fmt::Debug for Drain<'_> {
3748    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3749        f.debug_tuple("Drain").field(&self.as_str()).finish()
3750    }
3751}
3752
3753#[stable(feature = "drain", since = "1.6.0")]
3754unsafe impl Sync for Drain<'_> {}
3755#[stable(feature = "drain", since = "1.6.0")]
3756unsafe impl Send for Drain<'_> {}
3757
3758#[stable(feature = "drain", since = "1.6.0")]
3759impl Drop for Drain<'_> {
3760    fn drop(&mut self) {
3761        // Use Vec::drain. "Reaffirm" the bounds checks to avoid
3762        // panic code being inserted again.
3763        // SAFETY: We only use the returned Vec to call drain.
3764        let self_vec = unsafe { &mut *(*self.string).as_mut_vec() };
3765        if self.start <= self.end && self.end <= self_vec.len() {
3766            self_vec.drain(self.start..self.end);
3767        }
3768    }
3769}
3770
3771impl<'a> Drain<'a> {
3772    /// Returns the remaining (sub)string of this iterator as a slice.
3773    ///
3774    /// # Examples
3775    ///
3776    /// ```
3777    /// let mut s = String::from("abc");
3778    /// let mut drain = s.drain(..);
3779    /// assert_eq!(drain.as_str(), "abc");
3780    /// let _ = drain.next().unwrap();
3781    /// assert_eq!(drain.as_str(), "bc");
3782    /// ```
3783    #[must_use]
3784    #[stable(feature = "string_drain_as_str", since = "1.55.0")]
3785    pub fn as_str(&self) -> &str {
3786        self.iter.as_str()
3787    }
3788}
3789
3790#[stable(feature = "string_drain_as_str", since = "1.55.0")]
3791impl<'a> AsRef<str> for Drain<'a> {
3792    fn as_ref(&self) -> &str {
3793        self.as_str()
3794    }
3795}
3796
3797#[stable(feature = "string_drain_as_str", since = "1.55.0")]
3798impl<'a> AsRef<[u8]> for Drain<'a> {
3799    fn as_ref(&self) -> &[u8] {
3800        self.as_str().as_bytes()
3801    }
3802}
3803
3804#[stable(feature = "drain", since = "1.6.0")]
3805impl Iterator for Drain<'_> {
3806    type Item = char;
3807
3808    #[inline]
3809    fn next(&mut self) -> Option<char> {
3810        self.iter.next()
3811    }
3812
3813    fn size_hint(&self) -> (usize, Option<usize>) {
3814        self.iter.size_hint()
3815    }
3816
3817    #[inline]
3818    fn last(mut self) -> Option<char> {
3819        self.next_back()
3820    }
3821}
3822
3823#[stable(feature = "drain", since = "1.6.0")]
3824impl DoubleEndedIterator for Drain<'_> {
3825    #[inline]
3826    fn next_back(&mut self) -> Option<char> {
3827        self.iter.next_back()
3828    }
3829}
3830
3831#[stable(feature = "fused", since = "1.26.0")]
3832impl FusedIterator for Drain<'_> {}
3833
3834#[cfg(not(no_global_oom_handling))]
3835#[stable(feature = "from_char_for_string", since = "1.46.0")]
3836impl From<char> for String {
3837    /// Allocates an owned [`String`] from a single character.
3838    ///
3839    /// # Example
3840    /// ```rust
3841    /// let c: char = 'a';
3842    /// let s: String = String::from(c);
3843    /// assert_eq!("a", &s[..]);
3844    /// ```
3845    #[inline]
3846    fn from(c: char) -> Self {
3847        c.to_string()
3848    }
3849}