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, 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        struct SetLenOnDrop<'a> {
1701            s: &'a mut String,
1702            idx: usize,
1703            del_bytes: usize,
1704        }
1705
1706        impl<'a> Drop for SetLenOnDrop<'a> {
1707            fn drop(&mut self) {
1708                let new_len = self.idx - self.del_bytes;
1709                debug_assert!(new_len <= self.s.len());
1710                // SAFETY: Restore the string length to the number of bytes written so far.
1711                unsafe { self.s.vec.set_len(new_len) };
1712            }
1713        }
1714
1715        let len = self.len();
1716        let mut guard = SetLenOnDrop { s: self, idx: 0, del_bytes: 0 };
1717
1718        while guard.idx < len {
1719            let ch =
1720                // SAFETY: `guard.idx` is positive-or-zero and less that len so the `get_unchecked`
1721                // is in bound. `self` is valid UTF-8 like string and the returned slice starts at
1722                // a unicode code point so the `Chars` always return one character.
1723                unsafe { guard.s.get_unchecked(guard.idx..len).chars().next().unwrap_unchecked() };
1724            let ch_len = ch.len_utf8();
1725
1726            if !f(ch) {
1727                guard.del_bytes += ch_len;
1728            } else if guard.del_bytes > 0 {
1729                // SAFETY: `guard.idx` is in bound and `guard.del_bytes` represent the number of
1730                // bytes that are erased from the string so the resulting `guard.idx -
1731                // guard.del_bytes` always represent a valid unicode code point.
1732                //
1733                // `guard.del_bytes` >= `ch.len_utf8()`, so taking a slice with `ch.len_utf8()` len
1734                // is safe.
1735                ch.encode_utf8(unsafe {
1736                    crate::slice::from_raw_parts_mut(
1737                        guard.s.as_mut_ptr().add(guard.idx - guard.del_bytes),
1738                        ch.len_utf8(),
1739                    )
1740                });
1741            }
1742
1743            // Point idx to the next char
1744            guard.idx += ch_len;
1745        }
1746
1747        drop(guard);
1748    }
1749
1750    /// Inserts a character into this `String` at byte position `idx`.
1751    ///
1752    /// Reallocates if `self.capacity()` is insufficient, which may involve copying all
1753    /// `self.capacity()` bytes. Makes space for the insertion by copying all bytes of
1754    /// `&self[idx..]` to new positions.
1755    ///
1756    /// Note that calling this in a loop can result in quadratic behavior.
1757    ///
1758    /// # Panics
1759    ///
1760    /// Panics if `idx` is larger than the `String`'s length, or if it does not
1761    /// lie on a [`char`] boundary.
1762    ///
1763    /// # Examples
1764    ///
1765    /// ```
1766    /// let mut s = String::with_capacity(3);
1767    ///
1768    /// s.insert(0, 'f');
1769    /// s.insert(1, 'o');
1770    /// s.insert(2, 'o');
1771    ///
1772    /// assert_eq!("foo", s);
1773    /// ```
1774    #[cfg(not(no_global_oom_handling))]
1775    #[inline]
1776    #[track_caller]
1777    #[stable(feature = "rust1", since = "1.0.0")]
1778    #[rustc_confusables("set")]
1779    pub fn insert(&mut self, idx: usize, ch: char) {
1780        assert!(self.is_char_boundary(idx));
1781
1782        let len = self.len();
1783        let ch_len = ch.len_utf8();
1784        self.reserve(ch_len);
1785
1786        // SAFETY: Move the bytes starting from `idx` to their new location `ch_len`
1787        // bytes ahead. This is safe because sufficient capacity was reserved, and `idx`
1788        // is a char boundary.
1789        unsafe {
1790            ptr::copy(
1791                self.vec.as_ptr().add(idx),
1792                self.vec.as_mut_ptr().add(idx + ch_len),
1793                len - idx,
1794            );
1795        }
1796
1797        // SAFETY: Encode the character into the vacated region if `idx != len`,
1798        // or into the uninitialized spare capacity otherwise.
1799        unsafe {
1800            core::char::encode_utf8_raw_unchecked(ch as u32, self.vec.as_mut_ptr().add(idx));
1801        }
1802
1803        // SAFETY: Update the length to include the newly added bytes.
1804        unsafe {
1805            self.vec.set_len(len + ch_len);
1806        }
1807    }
1808
1809    /// Inserts a string slice into this `String` at byte position `idx`.
1810    ///
1811    /// Reallocates if `self.capacity()` is insufficient, which may involve copying all
1812    /// `self.capacity()` bytes. Makes space for the insertion by copying all bytes of
1813    /// `&self[idx..]` to new positions.
1814    ///
1815    /// Note that calling this in a loop can result in quadratic behavior.
1816    ///
1817    /// # Panics
1818    ///
1819    /// Panics if `idx` is larger than the `String`'s length, or if it does not
1820    /// lie on a [`char`] boundary.
1821    ///
1822    /// # Examples
1823    ///
1824    /// ```
1825    /// let mut s = String::from("bar");
1826    ///
1827    /// s.insert_str(0, "foo");
1828    ///
1829    /// assert_eq!("foobar", s);
1830    /// ```
1831    #[cfg(not(no_global_oom_handling))]
1832    #[inline]
1833    #[track_caller]
1834    #[stable(feature = "insert_str", since = "1.16.0")]
1835    #[rustc_diagnostic_item = "string_insert_str"]
1836    pub fn insert_str(&mut self, idx: usize, string: &str) {
1837        assert!(self.is_char_boundary(idx));
1838
1839        let len = self.len();
1840        let amt = string.len();
1841        self.reserve(amt);
1842
1843        // SAFETY: Move the bytes starting from `idx` to their new location `amt` bytes
1844        // ahead. This is safe because sufficient capacity was just reserved, and `idx`
1845        // is a char boundary.
1846        unsafe {
1847            ptr::copy(self.vec.as_ptr().add(idx), self.vec.as_mut_ptr().add(idx + amt), len - idx);
1848        }
1849
1850        // SAFETY: Copy the new string slice into the vacated region if `idx != len`,
1851        // or into the uninitialized spare capacity otherwise. The borrow checker
1852        // ensures that the source and destination do not overlap.
1853        unsafe {
1854            ptr::copy_nonoverlapping(string.as_ptr(), self.vec.as_mut_ptr().add(idx), amt);
1855        }
1856
1857        // SAFETY: Update the length to include the newly added bytes.
1858        unsafe {
1859            self.vec.set_len(len + amt);
1860        }
1861    }
1862
1863    /// Returns a mutable reference to the contents of this `String`.
1864    ///
1865    /// # Safety
1866    ///
1867    /// This function is unsafe because the returned `&mut Vec` allows writing
1868    /// bytes which are not valid UTF-8. If this constraint is violated, using
1869    /// the original `String` after dropping the `&mut Vec` may violate memory
1870    /// safety, as the rest of the standard library assumes that `String`s are
1871    /// valid UTF-8.
1872    ///
1873    /// # Examples
1874    ///
1875    /// ```
1876    /// let mut s = String::from("hello");
1877    ///
1878    /// unsafe {
1879    ///     let vec = s.as_mut_vec();
1880    ///     assert_eq!(&[104, 101, 108, 108, 111][..], &vec[..]);
1881    ///
1882    ///     vec.reverse();
1883    /// }
1884    /// assert_eq!(s, "olleh");
1885    /// ```
1886    #[inline]
1887    #[stable(feature = "rust1", since = "1.0.0")]
1888    #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")]
1889    pub const unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1890        &mut self.vec
1891    }
1892
1893    /// Returns the length of this `String`, in bytes, not [`char`]s or
1894    /// graphemes. In other words, it might not be what a human considers the
1895    /// length of the string.
1896    ///
1897    /// # Examples
1898    ///
1899    /// ```
1900    /// let a = String::from("foo");
1901    /// assert_eq!(a.len(), 3);
1902    ///
1903    /// let fancy_f = String::from("Ζ’oo");
1904    /// assert_eq!(fancy_f.len(), 4);
1905    /// assert_eq!(fancy_f.chars().count(), 3);
1906    /// ```
1907    #[inline]
1908    #[must_use]
1909    #[stable(feature = "rust1", since = "1.0.0")]
1910    #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")]
1911    #[rustc_confusables("length", "size")]
1912    #[rustc_no_implicit_autorefs]
1913    pub const fn len(&self) -> usize {
1914        self.vec.len()
1915    }
1916
1917    /// Returns `true` if this `String` has a length of zero, and `false` otherwise.
1918    ///
1919    /// # Examples
1920    ///
1921    /// ```
1922    /// let mut v = String::new();
1923    /// assert!(v.is_empty());
1924    ///
1925    /// v.push('a');
1926    /// assert!(!v.is_empty());
1927    /// ```
1928    #[inline]
1929    #[must_use]
1930    #[stable(feature = "rust1", since = "1.0.0")]
1931    #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")]
1932    #[rustc_no_implicit_autorefs]
1933    pub const fn is_empty(&self) -> bool {
1934        self.len() == 0
1935    }
1936
1937    /// Splits the string into two at the given byte index.
1938    ///
1939    /// Returns a newly allocated `String`. `self` contains bytes `[0, at)`, and
1940    /// the returned `String` contains bytes `[at, len)`. `at` must be on the
1941    /// boundary of a UTF-8 code point.
1942    ///
1943    /// Note that the capacity of `self` does not change.
1944    ///
1945    /// # Panics
1946    ///
1947    /// Panics if `at` is not on a `UTF-8` code point boundary, or if it is beyond the last
1948    /// code point of the string.
1949    ///
1950    /// # Examples
1951    ///
1952    /// ```
1953    /// # fn main() {
1954    /// let mut hello = String::from("Hello, World!");
1955    /// let world = hello.split_off(7);
1956    /// assert_eq!(hello, "Hello, ");
1957    /// assert_eq!(world, "World!");
1958    /// # }
1959    /// ```
1960    #[cfg(not(no_global_oom_handling))]
1961    #[inline]
1962    #[track_caller]
1963    #[stable(feature = "string_split_off", since = "1.16.0")]
1964    #[must_use = "use `.truncate()` if you don't need the other half"]
1965    pub fn split_off(&mut self, at: usize) -> String {
1966        assert!(self.is_char_boundary(at));
1967        let other = self.vec.split_off(at);
1968        // SAFETY: `other` contains only valid UTF-8 because `at` is on a `UTF-8` code point boundary.
1969        unsafe { String::from_utf8_unchecked(other) }
1970    }
1971
1972    /// Truncates this `String`, removing all contents.
1973    ///
1974    /// While this means the `String` will have a length of zero, it does not
1975    /// touch its capacity.
1976    ///
1977    /// # Examples
1978    ///
1979    /// ```
1980    /// let mut s = String::from("foo");
1981    ///
1982    /// s.clear();
1983    ///
1984    /// assert!(s.is_empty());
1985    /// assert_eq!(0, s.len());
1986    /// assert_eq!(3, s.capacity());
1987    /// ```
1988    #[inline]
1989    #[stable(feature = "rust1", since = "1.0.0")]
1990    pub fn clear(&mut self) {
1991        self.vec.clear()
1992    }
1993
1994    /// Removes the specified range from the string in bulk, returning all
1995    /// removed characters as an iterator.
1996    ///
1997    /// The returned iterator keeps a mutable borrow on the string to optimize
1998    /// its implementation.
1999    ///
2000    /// # Panics
2001    ///
2002    /// Panics if the range has `start_bound > end_bound`, or, if the range is
2003    /// bounded on either end and does not lie on a [`char`] boundary.
2004    ///
2005    /// # Leaking
2006    ///
2007    /// If the returned iterator goes out of scope without being dropped (due to
2008    /// [`core::mem::forget`], for example), the string may still contain a copy
2009    /// of any drained characters, or may have lost characters arbitrarily,
2010    /// including characters outside the range.
2011    ///
2012    /// # Examples
2013    ///
2014    /// ```
2015    /// let mut s = String::from("Ξ± is alpha, Ξ² is beta");
2016    /// let beta_offset = s.find('Ξ²').unwrap_or(s.len());
2017    ///
2018    /// // Remove the range up until the Ξ² from the string
2019    /// let t: String = s.drain(..beta_offset).collect();
2020    /// assert_eq!(t, "Ξ± is alpha, ");
2021    /// assert_eq!(s, "Ξ² is beta");
2022    ///
2023    /// // A full range clears the string, like `clear()` does
2024    /// s.drain(..);
2025    /// assert_eq!(s, "");
2026    /// ```
2027    #[stable(feature = "drain", since = "1.6.0")]
2028    #[track_caller]
2029    pub fn drain<R>(&mut self, range: R) -> Drain<'_>
2030    where
2031        R: RangeBounds<usize>,
2032    {
2033        // Memory safety
2034        //
2035        // The String version of Drain does not have the memory safety issues
2036        // of the vector version. The data is just plain bytes.
2037        // Because the range removal happens in Drop, if the Drain iterator is leaked,
2038        // the removal will not happen.
2039        let Range { start, end } = slice::range(range, ..self.len());
2040        assert!(self.is_char_boundary(start));
2041        assert!(self.is_char_boundary(end));
2042
2043        // Take out two simultaneous borrows. The &mut String won't be accessed
2044        // until iteration is over, in Drop.
2045        let self_ptr = self as *mut _;
2046        // SAFETY: `slice::range` and `is_char_boundary` do the appropriate bounds checks.
2047        let chars_iter = unsafe { self.get_unchecked(start..end) }.chars();
2048
2049        Drain { start, end, iter: chars_iter, string: self_ptr }
2050    }
2051
2052    /// Converts a `String` into an iterator over the [`char`]s of the string.
2053    ///
2054    /// As a string consists of valid UTF-8, we can iterate through a string
2055    /// by [`char`]. This method returns such an iterator.
2056    ///
2057    /// It's important to remember that [`char`] represents a Unicode Scalar
2058    /// Value, and might not match your idea of what a 'character' is. Iteration
2059    /// over grapheme clusters may be what you actually want. That functionality
2060    /// is not provided by Rust's standard library, check crates.io instead.
2061    ///
2062    /// # Examples
2063    ///
2064    /// Basic usage:
2065    ///
2066    /// ```
2067    /// let word = String::from("goodbye");
2068    ///
2069    /// let mut chars = word.into_chars();
2070    ///
2071    /// assert_eq!(Some('g'), chars.next());
2072    /// assert_eq!(Some('o'), chars.next());
2073    /// assert_eq!(Some('o'), chars.next());
2074    /// assert_eq!(Some('d'), chars.next());
2075    /// assert_eq!(Some('b'), chars.next());
2076    /// assert_eq!(Some('y'), chars.next());
2077    /// assert_eq!(Some('e'), chars.next());
2078    ///
2079    /// assert_eq!(None, chars.next());
2080    /// ```
2081    ///
2082    /// Remember, [`char`]s might not match your intuition about characters:
2083    ///
2084    /// ```
2085    /// let y = String::from("y̆");
2086    ///
2087    /// let mut chars = y.into_chars();
2088    ///
2089    /// assert_eq!(Some('y'), chars.next()); // not 'y̆'
2090    /// assert_eq!(Some('\u{0306}'), chars.next());
2091    ///
2092    /// assert_eq!(None, chars.next());
2093    /// ```
2094    ///
2095    /// [`char`]: prim@char
2096    #[inline]
2097    #[must_use = "`self` will be dropped if the result is not used"]
2098    #[stable(feature = "string_into_chars", since = "1.101.0")]
2099    pub fn into_chars(self) -> IntoChars {
2100        IntoChars { bytes: self.into_bytes().into_iter() }
2101    }
2102
2103    /// Removes the specified range in the string,
2104    /// and replaces it with the given string.
2105    /// The given string doesn't need to be the same length as the range.
2106    ///
2107    /// # Panics
2108    ///
2109    /// Panics if the range has `start_bound > end_bound`, or, if the range is
2110    /// bounded on either end and does not lie on a [`char`] boundary.
2111    ///
2112    /// # Examples
2113    ///
2114    /// ```
2115    /// let mut s = String::from("Ξ± is alpha, Ξ² is beta");
2116    /// let beta_offset = s.find('Ξ²').unwrap_or(s.len());
2117    ///
2118    /// // Replace the range up until the Ξ² from the string
2119    /// s.replace_range(..beta_offset, "Ξ‘ is capital alpha; ");
2120    /// assert_eq!(s, "Ξ‘ is capital alpha; Ξ² is beta");
2121    /// ```
2122    #[cfg(not(no_global_oom_handling))]
2123    #[stable(feature = "splice", since = "1.27.0")]
2124    #[track_caller]
2125    pub fn replace_range<R>(&mut self, range: R, replace_with: &str)
2126    where
2127        R: RangeBounds<usize>,
2128    {
2129        // We avoid #81138 (nondeterministic RangeBounds impls) because we only use `range` once, here.
2130        let checked_range = slice::range(range, ..self.len());
2131
2132        assert!(
2133            self.is_char_boundary(checked_range.start),
2134            "start of range should be a character boundary"
2135        );
2136        assert!(
2137            self.is_char_boundary(checked_range.end),
2138            "end of range should be a character boundary"
2139        );
2140
2141        if replace_with.len() > checked_range.len() {
2142            self.reserve(replace_with.len() - checked_range.len());
2143        }
2144        // SAFETY: We ensure that we're not replacing across a char boundary and
2145        // that the new contents are valid UTF-8. The only potentially-unsound
2146        // unwind from `splice` that would leave the string in an invalid state
2147        // would be from an error growing the allocation, which we protect against
2148        // by reserving it preemptively.
2149        unsafe { self.as_mut_vec() }.splice(checked_range, replace_with.bytes());
2150    }
2151
2152    /// Replaces the leftmost occurrence of a pattern with another string, in-place.
2153    ///
2154    /// This method can be preferred over [`string = string.replacen(..., 1);`][replacen],
2155    /// as it can use the `String`'s existing capacity to prevent a reallocation if
2156    /// sufficient space is available.
2157    ///
2158    /// # Examples
2159    ///
2160    /// Basic usage:
2161    ///
2162    /// ```
2163    /// #![feature(string_replace_in_place)]
2164    ///
2165    /// let mut s = String::from("Test Results: ❌❌❌");
2166    ///
2167    /// // Replace the leftmost ❌ with a βœ…
2168    /// s.replace_first('❌', "βœ…");
2169    /// assert_eq!(s, "Test Results: βœ…βŒβŒ");
2170    /// ```
2171    ///
2172    /// [replacen]: ../../std/primitive.str.html#method.replacen
2173    #[cfg(not(no_global_oom_handling))]
2174    #[unstable(feature = "string_replace_in_place", issue = "147949")]
2175    pub fn replace_first<P: Pattern>(&mut self, from: P, to: &str) {
2176        let range = match self.match_indices(from).next() {
2177            Some((start, match_str)) => start..start + match_str.len(),
2178            None => return,
2179        };
2180
2181        self.replace_range(range, to);
2182    }
2183
2184    /// Replaces the rightmost occurrence of a pattern with another string, in-place.
2185    ///
2186    /// # Examples
2187    ///
2188    /// Basic usage:
2189    ///
2190    /// ```
2191    /// #![feature(string_replace_in_place)]
2192    ///
2193    /// let mut s = String::from("Test Results: ❌❌❌");
2194    ///
2195    /// // Replace the rightmost ❌ with a βœ…
2196    /// s.replace_last('❌', "βœ…");
2197    /// assert_eq!(s, "Test Results: βŒβŒβœ…");
2198    /// ```
2199    #[cfg(not(no_global_oom_handling))]
2200    #[unstable(feature = "string_replace_in_place", issue = "147949")]
2201    pub fn replace_last<P: Pattern>(&mut self, from: P, to: &str)
2202    where
2203        for<'a> P::Searcher<'a>: core::str::pattern::ReverseSearcher<'a>,
2204    {
2205        let range = match self.rmatch_indices(from).next() {
2206            Some((start, match_str)) => start..start + match_str.len(),
2207            None => return,
2208        };
2209
2210        self.replace_range(range, to);
2211    }
2212
2213    /// Converts this `String` into a <code>[Box]<[str]></code>.
2214    ///
2215    /// Before doing the conversion, this method discards excess capacity like [`shrink_to_fit`].
2216    /// Note that this call may reallocate and copy the bytes of the string.
2217    ///
2218    /// [`shrink_to_fit`]: String::shrink_to_fit
2219    /// [str]: prim@str "str"
2220    ///
2221    /// # Examples
2222    ///
2223    /// ```
2224    /// let s = String::from("hello");
2225    ///
2226    /// let b = s.into_boxed_str();
2227    /// ```
2228    #[cfg(not(no_global_oom_handling))]
2229    #[stable(feature = "box_str", since = "1.4.0")]
2230    #[must_use = "`self` will be dropped if the result is not used"]
2231    #[inline]
2232    pub fn into_boxed_str(self) -> Box<str> {
2233        let slice = self.vec.into_boxed_slice();
2234        // SAFETY: `slice` contains only valid UTF-8 because `String` is guaranteed to be valid UTF-8.
2235        unsafe { from_boxed_utf8_unchecked(slice) }
2236    }
2237
2238    /// Consumes and leaks the `String`, returning a mutable reference to the contents,
2239    /// `&'a mut str`.
2240    ///
2241    /// The caller has free choice over the returned lifetime, including `'static`. Indeed,
2242    /// this function is ideally used for data that lives for the remainder of the program's life,
2243    /// as dropping the returned reference will cause a memory leak.
2244    ///
2245    /// It does not reallocate or shrink the `String`, so the leaked allocation may include unused
2246    /// capacity that is not part of the returned slice. If you want to discard excess capacity,
2247    /// call [`into_boxed_str`], and then [`Box::leak`] instead. However, keep in mind that
2248    /// trimming the capacity may result in a reallocation and copy.
2249    ///
2250    /// [`into_boxed_str`]: Self::into_boxed_str
2251    ///
2252    /// # Examples
2253    ///
2254    /// ```
2255    /// let x = String::from("bucket");
2256    /// let static_ref: &'static mut str = x.leak();
2257    /// assert_eq!(static_ref, "bucket");
2258    /// # // FIXME(https://github.com/rust-lang/miri/issues/3670):
2259    /// # // use -Zmiri-disable-leak-check instead of unleaking in tests meant to leak.
2260    /// # drop(unsafe { Box::from_raw(static_ref) });
2261    /// ```
2262    #[stable(feature = "string_leak", since = "1.72.0")]
2263    #[inline]
2264    pub fn leak<'a>(self) -> &'a mut str {
2265        let slice = self.vec.leak();
2266        // SAFETY: `slice` contains only valid UTF-8 because `String` is guaranteed to be valid UTF-8.
2267        unsafe { from_utf8_unchecked_mut(slice) }
2268    }
2269}
2270
2271impl FromUtf8Error {
2272    /// Returns a slice of [`u8`]s bytes that were attempted to convert to a `String`.
2273    ///
2274    /// # Examples
2275    ///
2276    /// ```
2277    /// // some invalid bytes, in a vector
2278    /// let bytes = vec![0, 159];
2279    ///
2280    /// let value = String::from_utf8(bytes);
2281    ///
2282    /// assert_eq!(&[0, 159], value.unwrap_err().as_bytes());
2283    /// ```
2284    #[must_use]
2285    #[stable(feature = "from_utf8_error_as_bytes", since = "1.26.0")]
2286    pub fn as_bytes(&self) -> &[u8] {
2287        &self.bytes[..]
2288    }
2289
2290    /// Converts the bytes into a `String` lossily, substituting invalid UTF-8
2291    /// sequences with replacement characters.
2292    ///
2293    /// See [`String::from_utf8_lossy`] for more details on replacement of
2294    /// invalid sequences, and [`String::from_utf8_lossy_owned`] for the
2295    /// `String` function which corresponds to this function.
2296    ///
2297    /// This is useful in conjunction with [`String::from_utf8`] when you need
2298    /// to branch on whether the bytes are valid UTF-8, but still want to
2299    /// recover a lossily converted `String` in the error case. Use
2300    /// [`String::from_utf8_lossy_owned`] if you always need a lossily converted
2301    /// `String`.
2302    ///
2303    /// Since the original [`String::from_utf8`] error records where validation
2304    /// stopped, this method does not need to re-check the already valid prefix
2305    /// of the byte sequence.
2306    ///
2307    /// # Examples
2308    ///
2309    /// ```
2310    /// // some invalid bytes
2311    /// let input: Vec<u8> = b"Hello \xF0\x90\x80World".into();
2312    ///
2313    /// let (output, had_invalid_utf8) = match String::from_utf8(input) {
2314    ///     Ok(output) => (output, false),
2315    ///     Err(error) => {
2316    ///         // The bytes were not valid UTF-8, but we can still recover a string.
2317    ///         (error.into_utf8_lossy(), true)
2318    ///     }
2319    /// };
2320    ///
2321    /// assert_eq!(String::from("Hello οΏ½World"), output);
2322    /// assert!(had_invalid_utf8);
2323    /// ```
2324    #[must_use]
2325    #[cfg(not(no_global_oom_handling))]
2326    #[stable(feature = "string_from_utf8_lossy_owned", since = "1.99.0")]
2327    pub fn into_utf8_lossy(self) -> String {
2328        const REPLACEMENT: &str = "\u{FFFD}";
2329
2330        let mut res = {
2331            let mut v = Vec::with_capacity(self.bytes.len());
2332
2333            // `Utf8Error::valid_up_to` returns the maximum index of validated
2334            // UTF-8 bytes. Copy the valid bytes into the output buffer.
2335            v.extend_from_slice(&self.bytes[..self.error.valid_up_to()]);
2336
2337            // SAFETY: This is safe because the only bytes present in the buffer
2338            // were validated as UTF-8 by the call to `String::from_utf8` which
2339            // produced this `FromUtf8Error`.
2340            unsafe { String::from_utf8_unchecked(v) }
2341        };
2342
2343        let iter = self.bytes[self.error.valid_up_to()..].utf8_chunks();
2344
2345        for chunk in iter {
2346            res.push_str(chunk.valid());
2347            if !chunk.invalid().is_empty() {
2348                res.push_str(REPLACEMENT);
2349            }
2350        }
2351
2352        res
2353    }
2354
2355    /// Returns the bytes that were attempted to convert to a `String`.
2356    ///
2357    /// This method is carefully constructed to avoid allocation. It will
2358    /// consume the error, moving out the bytes, so that a copy of the bytes
2359    /// does not need to be made.
2360    ///
2361    /// # Examples
2362    ///
2363    /// ```
2364    /// // some invalid bytes, in a vector
2365    /// let bytes = vec![0, 159];
2366    ///
2367    /// let value = String::from_utf8(bytes);
2368    ///
2369    /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
2370    /// ```
2371    #[must_use = "`self` will be dropped if the result is not used"]
2372    #[stable(feature = "rust1", since = "1.0.0")]
2373    pub fn into_bytes(self) -> Vec<u8> {
2374        self.bytes
2375    }
2376
2377    /// Fetch a `Utf8Error` to get more details about the conversion failure.
2378    ///
2379    /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
2380    /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
2381    /// an analogue to `FromUtf8Error`. See its documentation for more details
2382    /// on using it.
2383    ///
2384    /// [`std::str`]: core::str "std::str"
2385    /// [`&str`]: prim@str "&str"
2386    ///
2387    /// # Examples
2388    ///
2389    /// ```
2390    /// // some invalid bytes, in a vector
2391    /// let bytes = vec![0, 159];
2392    ///
2393    /// let error = String::from_utf8(bytes).unwrap_err().utf8_error();
2394    ///
2395    /// // the first byte is invalid here
2396    /// assert_eq!(1, error.valid_up_to());
2397    /// ```
2398    #[must_use]
2399    #[stable(feature = "rust1", since = "1.0.0")]
2400    pub fn utf8_error(&self) -> Utf8Error {
2401        self.error
2402    }
2403}
2404
2405#[stable(feature = "rust1", since = "1.0.0")]
2406impl fmt::Display for FromUtf8Error {
2407    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2408        fmt::Display::fmt(&self.error, f)
2409    }
2410}
2411
2412#[stable(feature = "rust1", since = "1.0.0")]
2413impl fmt::Display for FromUtf16Error {
2414    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2415        match self.kind {
2416            FromUtf16ErrorKind::LoneSurrogate => "invalid utf-16: lone surrogate found",
2417            FromUtf16ErrorKind::OddBytes => "invalid utf-16: odd number of bytes",
2418        }
2419        .fmt(f)
2420    }
2421}
2422
2423#[stable(feature = "rust1", since = "1.0.0")]
2424impl Error for FromUtf8Error {}
2425
2426#[stable(feature = "rust1", since = "1.0.0")]
2427impl Error for FromUtf16Error {}
2428
2429#[cfg(not(no_global_oom_handling))]
2430#[stable(feature = "rust1", since = "1.0.0")]
2431impl Clone for String {
2432    fn clone(&self) -> Self {
2433        String { vec: self.vec.clone() }
2434    }
2435
2436    /// Clones the contents of `source` into `self`.
2437    ///
2438    /// This method is preferred over simply assigning `source.clone()` to `self`,
2439    /// as it avoids reallocation if possible.
2440    fn clone_from(&mut self, source: &Self) {
2441        self.vec.clone_from(&source.vec);
2442    }
2443}
2444
2445#[cfg(not(no_global_oom_handling))]
2446#[stable(feature = "rust1", since = "1.0.0")]
2447impl FromIterator<char> for String {
2448    fn from_iter<I: IntoIterator<Item = char>>(iter: I) -> String {
2449        FromCharIterSpec::to_string_spec(iter.into_iter())
2450    }
2451}
2452
2453#[cfg(not(no_global_oom_handling))]
2454trait FromCharIterSpec: Iterator<Item = char> {
2455    fn to_string_spec(self) -> String;
2456}
2457
2458#[cfg(not(no_global_oom_handling))]
2459impl<T> FromCharIterSpec for T
2460where
2461    T: Iterator<Item = char>,
2462{
2463    default fn to_string_spec(self) -> String {
2464        let mut buf = String::with_capacity(self.size_hint().0);
2465        buf.extend(self);
2466        buf
2467    }
2468}
2469
2470#[cfg(not(no_global_oom_handling))]
2471impl FromCharIterSpec for core::str::EscapeDefault<'_> {
2472    fn to_string_spec(self) -> String {
2473        // go through the ToString specialization
2474        self.to_string()
2475    }
2476}
2477
2478#[cfg(not(no_global_oom_handling))]
2479#[stable(feature = "string_from_iter_by_ref", since = "1.17.0")]
2480impl<'a> FromIterator<&'a char> for String {
2481    fn from_iter<I: IntoIterator<Item = &'a char>>(iter: I) -> String {
2482        let mut buf = String::new();
2483        buf.extend(iter);
2484        buf
2485    }
2486}
2487
2488#[cfg(not(no_global_oom_handling))]
2489#[stable(feature = "rust1", since = "1.0.0")]
2490impl<'a> FromIterator<&'a str> for String {
2491    fn from_iter<I: IntoIterator<Item = &'a str>>(iter: I) -> String {
2492        let mut buf = String::new();
2493        buf.extend(iter);
2494        buf
2495    }
2496}
2497
2498#[cfg(not(no_global_oom_handling))]
2499#[stable(feature = "extend_string", since = "1.4.0")]
2500impl FromIterator<String> for String {
2501    fn from_iter<I: IntoIterator<Item = String>>(iter: I) -> String {
2502        let mut iterator = iter.into_iter();
2503
2504        // Because we're iterating over `String`s, we can avoid at least
2505        // one allocation by getting the first string from the iterator
2506        // and appending to it all the subsequent strings.
2507        match iterator.next() {
2508            None => String::new(),
2509            Some(mut buf) => {
2510                buf.extend(iterator);
2511                buf
2512            }
2513        }
2514    }
2515}
2516
2517#[cfg(not(no_global_oom_handling))]
2518#[stable(feature = "box_str2", since = "1.45.0")]
2519impl<A: Allocator> FromIterator<Box<str, A>> for String {
2520    fn from_iter<I: IntoIterator<Item = Box<str, A>>>(iter: I) -> String {
2521        let mut buf = String::new();
2522        buf.extend(iter);
2523        buf
2524    }
2525}
2526
2527#[cfg(not(no_global_oom_handling))]
2528#[stable(feature = "herd_cows", since = "1.19.0")]
2529impl<'a> FromIterator<Cow<'a, str>> for String {
2530    fn from_iter<I: IntoIterator<Item = Cow<'a, str>>>(iter: I) -> String {
2531        let mut iterator = iter.into_iter();
2532
2533        // Because we're iterating over CoWs, we can (potentially) avoid at least
2534        // one allocation by getting the first item and appending to it all the
2535        // subsequent items.
2536        match iterator.next() {
2537            None => String::new(),
2538            Some(cow) => {
2539                let mut buf = cow.into_owned();
2540                buf.extend(iterator);
2541                buf
2542            }
2543        }
2544    }
2545}
2546
2547#[cfg(not(no_global_oom_handling))]
2548#[unstable(feature = "ascii_char", issue = "110998")]
2549impl FromIterator<core::ascii::Char> for String {
2550    fn from_iter<I: IntoIterator<Item = core::ascii::Char>>(iter: I) -> Self {
2551        let buf = iter.into_iter().map(core::ascii::Char::to_u8).collect();
2552        // SAFETY: `buf` is guaranteed to be valid UTF-8 because the `core::ascii::Char` type
2553        // only contains ASCII values (0x00-0x7F), which are valid UTF-8.
2554        unsafe { String::from_utf8_unchecked(buf) }
2555    }
2556}
2557
2558#[cfg(not(no_global_oom_handling))]
2559#[unstable(feature = "ascii_char", issue = "110998")]
2560impl<'a> FromIterator<&'a core::ascii::Char> for String {
2561    fn from_iter<I: IntoIterator<Item = &'a core::ascii::Char>>(iter: I) -> Self {
2562        let buf = iter.into_iter().copied().map(core::ascii::Char::to_u8).collect();
2563        // SAFETY: `buf` is guaranteed to be valid UTF-8 because the `core::ascii::Char` type
2564        // only contains ASCII values (0x00-0x7F), which are valid UTF-8.
2565        unsafe { String::from_utf8_unchecked(buf) }
2566    }
2567}
2568
2569#[cfg(not(no_global_oom_handling))]
2570#[stable(feature = "rust1", since = "1.0.0")]
2571impl Extend<char> for String {
2572    fn extend<I: IntoIterator<Item = char>>(&mut self, iter: I) {
2573        SpecExtendChars::spec_extend_into(iter, self);
2574    }
2575
2576    #[inline]
2577    fn extend_one(&mut self, c: char) {
2578        self.push(c);
2579    }
2580
2581    #[inline]
2582    fn extend_reserve(&mut self, additional: usize) {
2583        self.reserve(additional);
2584    }
2585}
2586
2587#[cfg(not(no_global_oom_handling))]
2588trait SpecExtendChars {
2589    fn spec_extend_into(self, s: &mut String);
2590}
2591
2592#[cfg(not(no_global_oom_handling))]
2593impl<T: IntoIterator<Item = char>> SpecExtendChars for T {
2594    default fn spec_extend_into(self, target: &mut String) {
2595        let iterator = self.into_iter();
2596        let (lower_bound, _) = iterator.size_hint();
2597        target.reserve(lower_bound);
2598        iterator.for_each(move |c| target.push(c));
2599    }
2600}
2601
2602#[cfg(not(no_global_oom_handling))]
2603impl SpecExtendChars for core::str::EscapeDefault<'_> {
2604    fn spec_extend_into(self, target: &mut String) {
2605        target.extend_from_escape_default(self);
2606    }
2607}
2608
2609#[cfg(not(no_global_oom_handling))]
2610#[stable(feature = "extend_ref", since = "1.2.0")]
2611impl<'a> Extend<&'a char> for String {
2612    fn extend<I: IntoIterator<Item = &'a char>>(&mut self, iter: I) {
2613        self.extend(iter.into_iter().cloned());
2614    }
2615
2616    #[inline]
2617    fn extend_one(&mut self, &c: &'a char) {
2618        self.push(c);
2619    }
2620
2621    #[inline]
2622    fn extend_reserve(&mut self, additional: usize) {
2623        self.reserve(additional);
2624    }
2625}
2626
2627#[cfg(not(no_global_oom_handling))]
2628#[stable(feature = "rust1", since = "1.0.0")]
2629impl<'a> Extend<&'a str> for String {
2630    fn extend<I: IntoIterator<Item = &'a str>>(&mut self, iter: I) {
2631        <I as SpecExtendStr>::spec_extend_into(iter, self)
2632    }
2633
2634    #[inline]
2635    fn extend_one(&mut self, s: &'a str) {
2636        self.push_str(s);
2637    }
2638}
2639
2640#[cfg(not(no_global_oom_handling))]
2641trait SpecExtendStr {
2642    fn spec_extend_into(self, s: &mut String);
2643}
2644
2645#[cfg(not(no_global_oom_handling))]
2646impl<'a, T: IntoIterator<Item = &'a str>> SpecExtendStr for T {
2647    default fn spec_extend_into(self, target: &mut String) {
2648        self.into_iter().for_each(move |s| target.push_str(s));
2649    }
2650}
2651
2652#[cfg(not(no_global_oom_handling))]
2653impl SpecExtendStr for [&str] {
2654    fn spec_extend_into(self, target: &mut String) {
2655        target.push_str_slice(&self);
2656    }
2657}
2658
2659#[cfg(not(no_global_oom_handling))]
2660impl<const N: usize> SpecExtendStr for [&str; N] {
2661    fn spec_extend_into(self, target: &mut String) {
2662        target.push_str_slice(&self[..]);
2663    }
2664}
2665
2666#[cfg(not(no_global_oom_handling))]
2667#[stable(feature = "box_str2", since = "1.45.0")]
2668impl<A: Allocator> Extend<Box<str, A>> for String {
2669    fn extend<I: IntoIterator<Item = Box<str, A>>>(&mut self, iter: I) {
2670        iter.into_iter().for_each(move |s| self.push_str(&s));
2671    }
2672}
2673
2674#[cfg(not(no_global_oom_handling))]
2675#[stable(feature = "extend_string", since = "1.4.0")]
2676impl Extend<String> for String {
2677    fn extend<I: IntoIterator<Item = String>>(&mut self, iter: I) {
2678        iter.into_iter().for_each(move |s| self.push_str(&s));
2679    }
2680
2681    #[inline]
2682    fn extend_one(&mut self, s: String) {
2683        self.push_str(&s);
2684    }
2685}
2686
2687#[cfg(not(no_global_oom_handling))]
2688#[stable(feature = "herd_cows", since = "1.19.0")]
2689impl<'a> Extend<Cow<'a, str>> for String {
2690    fn extend<I: IntoIterator<Item = Cow<'a, str>>>(&mut self, iter: I) {
2691        iter.into_iter().for_each(move |s| self.push_str(&s));
2692    }
2693
2694    #[inline]
2695    fn extend_one(&mut self, s: Cow<'a, str>) {
2696        self.push_str(&s);
2697    }
2698}
2699
2700#[cfg(not(no_global_oom_handling))]
2701#[unstable(feature = "ascii_char", issue = "110998")]
2702impl Extend<core::ascii::Char> for String {
2703    #[inline]
2704    fn extend<I: IntoIterator<Item = core::ascii::Char>>(&mut self, iter: I) {
2705        self.vec.extend(iter.into_iter().map(|c| c.to_u8()));
2706    }
2707
2708    #[inline]
2709    fn extend_one(&mut self, c: core::ascii::Char) {
2710        self.vec.push(c.to_u8());
2711    }
2712}
2713
2714#[cfg(not(no_global_oom_handling))]
2715#[unstable(feature = "ascii_char", issue = "110998")]
2716impl<'a> Extend<&'a core::ascii::Char> for String {
2717    #[inline]
2718    fn extend<I: IntoIterator<Item = &'a core::ascii::Char>>(&mut self, iter: I) {
2719        self.extend(iter.into_iter().cloned());
2720    }
2721
2722    #[inline]
2723    fn extend_one(&mut self, c: &'a core::ascii::Char) {
2724        self.vec.push(c.to_u8());
2725    }
2726}
2727
2728/// A convenience impl that delegates to the impl for `&str`.
2729///
2730/// # Examples
2731///
2732/// ```
2733/// assert_eq!(String::from("Hello world").find("world"), Some(6));
2734/// ```
2735#[unstable(
2736    feature = "pattern",
2737    reason = "API not fully fleshed out and ready to be stabilized",
2738    issue = "27721"
2739)]
2740impl<'b> Pattern for &'b String {
2741    type Searcher<'a> = <&'b str as Pattern>::Searcher<'a>;
2742
2743    fn into_searcher(self, haystack: &str) -> <&'b str as Pattern>::Searcher<'_> {
2744        self[..].into_searcher(haystack)
2745    }
2746
2747    #[inline]
2748    fn is_contained_in(self, haystack: &str) -> bool {
2749        self[..].is_contained_in(haystack)
2750    }
2751
2752    #[inline]
2753    fn is_prefix_of(self, haystack: &str) -> bool {
2754        self[..].is_prefix_of(haystack)
2755    }
2756
2757    #[inline]
2758    fn strip_prefix_of(self, haystack: &str) -> Option<&str> {
2759        self[..].strip_prefix_of(haystack)
2760    }
2761
2762    #[inline]
2763    fn is_suffix_of<'a>(self, haystack: &'a str) -> bool
2764    where
2765        Self::Searcher<'a>: core::str::pattern::ReverseSearcher<'a>,
2766    {
2767        self[..].is_suffix_of(haystack)
2768    }
2769
2770    #[inline]
2771    fn strip_suffix_of<'a>(self, haystack: &'a str) -> Option<&'a str>
2772    where
2773        Self::Searcher<'a>: core::str::pattern::ReverseSearcher<'a>,
2774    {
2775        self[..].strip_suffix_of(haystack)
2776    }
2777
2778    #[inline]
2779    fn as_utf8_pattern(&self) -> Option<Utf8Pattern<'_>> {
2780        Some(Utf8Pattern::StringPattern(self.as_str()))
2781    }
2782}
2783
2784macro_rules! impl_eq {
2785    ($lhs:ty, $rhs: ty) => {
2786        #[stable(feature = "rust1", since = "1.0.0")]
2787        impl PartialEq<$rhs> for $lhs {
2788            #[inline]
2789            fn eq(&self, other: &$rhs) -> bool {
2790                PartialEq::eq(&self[..], &other[..])
2791            }
2792            #[inline]
2793            fn ne(&self, other: &$rhs) -> bool {
2794                PartialEq::ne(&self[..], &other[..])
2795            }
2796        }
2797
2798        #[stable(feature = "rust1", since = "1.0.0")]
2799        impl PartialEq<$lhs> for $rhs {
2800            #[inline]
2801            fn eq(&self, other: &$lhs) -> bool {
2802                PartialEq::eq(&self[..], &other[..])
2803            }
2804            #[inline]
2805            fn ne(&self, other: &$lhs) -> bool {
2806                PartialEq::ne(&self[..], &other[..])
2807            }
2808        }
2809    };
2810}
2811
2812impl_eq! { String, str }
2813impl_eq! { String, &str }
2814#[cfg(not(no_global_oom_handling))]
2815impl_eq! { Cow<'_, str>, str }
2816#[cfg(not(no_global_oom_handling))]
2817impl_eq! { Cow<'_, str>, &'_ str }
2818#[cfg(not(no_global_oom_handling))]
2819impl_eq! { Cow<'_, str>, String }
2820
2821#[stable(feature = "rust1", since = "1.0.0")]
2822#[rustc_const_unstable(feature = "const_default", issue = "143894")]
2823const impl Default for String {
2824    /// Creates an empty `String`.
2825    #[inline]
2826    fn default() -> String {
2827        String::new()
2828    }
2829}
2830
2831#[stable(feature = "rust1", since = "1.0.0")]
2832impl fmt::Display for String {
2833    #[inline]
2834    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2835        fmt::Display::fmt(&**self, f)
2836    }
2837}
2838
2839#[stable(feature = "rust1", since = "1.0.0")]
2840impl fmt::Debug for String {
2841    #[inline]
2842    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2843        fmt::Debug::fmt(&**self, f)
2844    }
2845}
2846
2847#[stable(feature = "rust1", since = "1.0.0")]
2848impl hash::Hash for String {
2849    #[inline]
2850    fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
2851        (**self).hash(hasher)
2852    }
2853}
2854
2855/// Implements the `+` operator for concatenating two strings.
2856///
2857/// This consumes the `String` on the left-hand side and re-uses its buffer (growing it if
2858/// necessary). This is done to avoid allocating a new `String` and copying the entire contents on
2859/// every operation, which would lead to *O*(*n*^2) running time when building an *n*-byte string by
2860/// repeated concatenation.
2861///
2862/// The string on the right-hand side is only borrowed; its contents are copied into the returned
2863/// `String`.
2864///
2865/// # Examples
2866///
2867/// Concatenating two `String`s takes the first by value and borrows the second:
2868///
2869/// ```
2870/// let a = String::from("hello");
2871/// let b = String::from(" world");
2872/// let c = a + &b;
2873/// // `a` is moved and can no longer be used here.
2874/// ```
2875///
2876/// If you want to keep using the first `String`, you can clone it and append to the clone instead:
2877///
2878/// ```
2879/// let a = String::from("hello");
2880/// let b = String::from(" world");
2881/// let c = a.clone() + &b;
2882/// // `a` is still valid here.
2883/// ```
2884///
2885/// Concatenating `&str` slices can be done by converting the first to a `String`:
2886///
2887/// ```
2888/// let a = "hello";
2889/// let b = " world";
2890/// let c = a.to_string() + b;
2891/// ```
2892#[cfg(not(no_global_oom_handling))]
2893#[stable(feature = "rust1", since = "1.0.0")]
2894impl Add<&str> for String {
2895    type Output = String;
2896
2897    #[inline]
2898    fn add(mut self, other: &str) -> String {
2899        self.push_str(other);
2900        self
2901    }
2902}
2903
2904/// Implements the `+=` operator for appending to a `String`.
2905///
2906/// This has the same behavior as the [`push_str`][String::push_str] method.
2907#[cfg(not(no_global_oom_handling))]
2908#[stable(feature = "stringaddassign", since = "1.12.0")]
2909impl AddAssign<&str> for String {
2910    #[inline]
2911    fn add_assign(&mut self, other: &str) {
2912        self.push_str(other);
2913    }
2914}
2915
2916#[stable(feature = "rust1", since = "1.0.0")]
2917impl<I> ops::Index<I> for String
2918where
2919    I: slice::SliceIndex<str>,
2920{
2921    type Output = I::Output;
2922
2923    #[inline]
2924    fn index(&self, index: I) -> &I::Output {
2925        index.index(self.as_str())
2926    }
2927}
2928
2929#[stable(feature = "rust1", since = "1.0.0")]
2930impl<I> ops::IndexMut<I> for String
2931where
2932    I: slice::SliceIndex<str>,
2933{
2934    #[inline]
2935    fn index_mut(&mut self, index: I) -> &mut I::Output {
2936        index.index_mut(self.as_mut_str())
2937    }
2938}
2939
2940#[stable(feature = "rust1", since = "1.0.0")]
2941impl ops::Deref for String {
2942    type Target = str;
2943
2944    #[inline]
2945    fn deref(&self) -> &str {
2946        self.as_str()
2947    }
2948}
2949
2950#[unstable(feature = "deref_pure_trait", issue = "87121")]
2951unsafe impl ops::DerefPure for String {}
2952
2953#[stable(feature = "derefmut_for_string", since = "1.3.0")]
2954impl ops::DerefMut for String {
2955    #[inline]
2956    fn deref_mut(&mut self) -> &mut str {
2957        self.as_mut_str()
2958    }
2959}
2960
2961/// A type alias for [`!`].
2962///
2963/// This alias exists for backwards compatibility, and may be eventually deprecated.
2964#[stable(feature = "str_parse_error", since = "1.5.0")]
2965pub type ParseError = !;
2966
2967#[cfg(not(no_global_oom_handling))]
2968#[stable(feature = "rust1", since = "1.0.0")]
2969impl FromStr for String {
2970    type Err = !;
2971    #[inline]
2972    fn from_str(s: &str) -> Result<String, !> {
2973        Ok(String::from(s))
2974    }
2975}
2976
2977/// A trait for converting a value to a `String`.
2978///
2979/// This trait is automatically implemented for any type which implements the
2980/// [`Display`] trait. As such, `ToString` shouldn't be implemented directly:
2981/// [`Display`] should be implemented instead, and you get the `ToString`
2982/// implementation for free.
2983///
2984/// [`Display`]: fmt::Display
2985#[rustc_diagnostic_item = "ToString"]
2986#[stable(feature = "rust1", since = "1.0.0")]
2987pub trait ToString {
2988    /// Converts the given value to a `String`.
2989    ///
2990    /// # Examples
2991    ///
2992    /// ```
2993    /// let i = 5;
2994    /// let five = String::from("5");
2995    ///
2996    /// assert_eq!(five, i.to_string());
2997    /// ```
2998    #[rustc_conversion_suggestion]
2999    #[stable(feature = "rust1", since = "1.0.0")]
3000    #[rustc_diagnostic_item = "to_string_method"]
3001    fn to_string(&self) -> String;
3002}
3003
3004/// # Panics
3005///
3006/// In this implementation, the `to_string` method panics
3007/// if the `Display` implementation returns an error.
3008/// This indicates an incorrect `Display` implementation
3009/// since `fmt::Write for String` never returns an error itself.
3010#[cfg(not(no_global_oom_handling))]
3011#[stable(feature = "rust1", since = "1.0.0")]
3012impl<T: fmt::Display + ?Sized> ToString for T {
3013    #[inline]
3014    fn to_string(&self) -> String {
3015        <Self as SpecToString>::spec_to_string(self)
3016    }
3017}
3018
3019#[cfg(not(no_global_oom_handling))]
3020trait SpecToString {
3021    fn spec_to_string(&self) -> String;
3022}
3023
3024#[cfg(not(no_global_oom_handling))]
3025impl<T: fmt::Display + ?Sized> SpecToString for T {
3026    // A common guideline is to not inline generic functions. However,
3027    // removing `#[inline]` from this method causes non-negligible regressions.
3028    // See <https://github.com/rust-lang/rust/pull/74852>, the last attempt
3029    // to try to remove it.
3030    #[inline]
3031    default fn spec_to_string(&self) -> String {
3032        let mut buf = String::new();
3033        let mut formatter =
3034            core::fmt::Formatter::new(&mut buf, core::fmt::FormattingOptions::new());
3035        // Bypass format_args!() to avoid write_str with zero-length strs
3036        fmt::Display::fmt(self, &mut formatter)
3037            .expect("a Display implementation returned an error unexpectedly");
3038        buf
3039    }
3040}
3041
3042#[cfg(not(no_global_oom_handling))]
3043impl SpecToString for core::ascii::Char {
3044    #[inline]
3045    fn spec_to_string(&self) -> String {
3046        self.as_str().to_owned()
3047    }
3048}
3049
3050#[cfg(not(no_global_oom_handling))]
3051impl SpecToString for char {
3052    #[inline]
3053    fn spec_to_string(&self) -> String {
3054        String::from(self.encode_utf8(&mut [0; char::MAX_LEN_UTF8]))
3055    }
3056}
3057
3058#[cfg(not(no_global_oom_handling))]
3059impl SpecToString for bool {
3060    #[inline]
3061    fn spec_to_string(&self) -> String {
3062        String::from(if *self { "true" } else { "false" })
3063    }
3064}
3065
3066macro_rules! impl_to_string {
3067    ($($signed:ident, $unsigned:ident,)*) => {
3068        $(
3069        #[cfg(not(no_global_oom_handling))]
3070        #[cfg(not(feature = "optimize_for_size"))]
3071        impl SpecToString for $signed {
3072            #[inline]
3073            fn spec_to_string(&self) -> String {
3074                const SIZE: usize = $signed::MAX.ilog10() as usize + 1;
3075                let mut buf = [core::mem::MaybeUninit::<u8>::uninit(); SIZE];
3076                // Only difference between signed and unsigned are these 8 lines.
3077                let mut out;
3078                if *self < 0 {
3079                    out = String::with_capacity(SIZE + 1);
3080                    out.push('-');
3081                } else {
3082                    out = String::with_capacity(SIZE);
3083                }
3084
3085                // SAFETY: `buf` is always big enough to contain all the digits.
3086                unsafe { out.push_str(self.unsigned_abs()._fmt(&mut buf)); }
3087                out
3088            }
3089        }
3090        #[cfg(not(no_global_oom_handling))]
3091        #[cfg(not(feature = "optimize_for_size"))]
3092        impl SpecToString for $unsigned {
3093            #[inline]
3094            fn spec_to_string(&self) -> String {
3095                const SIZE: usize = $unsigned::MAX.ilog10() as usize + 1;
3096                let mut buf = [core::mem::MaybeUninit::<u8>::uninit(); SIZE];
3097
3098                // SAFETY: `buf` is always big enough to contain all the digits.
3099                unsafe { self._fmt(&mut buf).to_string() }
3100            }
3101        }
3102        )*
3103    }
3104}
3105
3106impl_to_string! {
3107    i8, u8,
3108    i16, u16,
3109    i32, u32,
3110    i64, u64,
3111    isize, usize,
3112    i128, u128,
3113}
3114
3115#[cfg(not(no_global_oom_handling))]
3116#[cfg(feature = "optimize_for_size")]
3117impl SpecToString for u8 {
3118    #[inline]
3119    fn spec_to_string(&self) -> String {
3120        let mut buf = String::with_capacity(3);
3121        let mut n = *self;
3122        if n >= 10 {
3123            if n >= 100 {
3124                buf.push((b'0' + n / 100) as char);
3125                n %= 100;
3126            }
3127            buf.push((b'0' + n / 10) as char);
3128            n %= 10;
3129        }
3130        buf.push((b'0' + n) as char);
3131        buf
3132    }
3133}
3134
3135#[cfg(not(no_global_oom_handling))]
3136#[cfg(feature = "optimize_for_size")]
3137impl SpecToString for i8 {
3138    #[inline]
3139    fn spec_to_string(&self) -> String {
3140        let mut buf = String::with_capacity(4);
3141        if self.is_negative() {
3142            buf.push('-');
3143        }
3144        let mut n = self.unsigned_abs();
3145        if n >= 10 {
3146            if n >= 100 {
3147                buf.push('1');
3148                n -= 100;
3149            }
3150            buf.push((b'0' + n / 10) as char);
3151            n %= 10;
3152        }
3153        buf.push((b'0' + n) as char);
3154        buf
3155    }
3156}
3157
3158#[cfg(not(no_global_oom_handling))]
3159macro_rules! to_string_str {
3160    {$($type:ty,)*} => {
3161        $(
3162            impl SpecToString for $type {
3163                #[inline]
3164                fn spec_to_string(&self) -> String {
3165                    let s: &str = self;
3166                    String::from(s)
3167                }
3168            }
3169        )*
3170    };
3171}
3172
3173#[cfg(not(no_global_oom_handling))]
3174to_string_str! {
3175    Cow<'_, str>,
3176    String,
3177    // Generic/generated code can sometimes have multiple, nested references
3178    // for strings, including `&&&str`s that would never be written
3179    // by hand.
3180    &&&&&&&&&&&&str,
3181    &&&&&&&&&&&str,
3182    &&&&&&&&&&str,
3183    &&&&&&&&&str,
3184    &&&&&&&&str,
3185    &&&&&&&str,
3186    &&&&&&str,
3187    &&&&&str,
3188    &&&&str,
3189    &&&str,
3190    &&str,
3191    &str,
3192    str,
3193}
3194
3195#[cfg(not(no_global_oom_handling))]
3196impl SpecToString for fmt::Arguments<'_> {
3197    #[inline]
3198    fn spec_to_string(&self) -> String {
3199        crate::fmt::format(*self)
3200    }
3201}
3202
3203#[cfg(not(no_global_oom_handling))]
3204impl SpecToString for core::str::EscapeDefault<'_> {
3205    fn spec_to_string(&self) -> String {
3206        let mut s = String::new();
3207        s.extend_from_escape_default(self.clone());
3208        s
3209    }
3210}
3211
3212#[cfg(not(no_global_oom_handling))]
3213impl String {
3214    #[inline]
3215    fn extend_from_escape_default(&mut self, escaper: core::str::EscapeDefault<'_>) {
3216        let (front, middle, tail) = escaper.into_parts();
3217        let lengths = front.as_ref().map_or_default(|f| f.size_hint().0)
3218            + middle.as_ref().map_or_default(|m| m.size_hint().0)
3219            + tail.as_ref().map_or_default(|t| t.size_hint().0);
3220        self.reserve(lengths);
3221
3222        if let Some(front) = front {
3223            self.extend(front);
3224        }
3225        if let Some(middle) = middle {
3226            /// Ensures a spare capacity of N bytes and then passes that as MaybeUninit
3227            /// slice to a closure that returns the bytes written, then
3228            /// updates the length.
3229            ///
3230            /// # Safety:
3231            ///
3232            /// The caller must initialize the number of bytes returned by the closure.
3233            #[inline]
3234            unsafe fn with_spare<const N: usize, T>(
3235                bytes: &mut Vec<u8>,
3236                then: impl FnOnce(&mut [MaybeUninit<T>; N]) -> usize,
3237            ) {
3238                const {
3239                    assert!(core::mem::size_of::<T>() == 1);
3240                }
3241                bytes.reserve(N);
3242                let old_len = bytes.len();
3243                // SAFETY: We reserved enough space for the requested number of bytes.
3244                unsafe {
3245                    let spare: &mut [MaybeUninit<T>; N] = bytes
3246                        .spare_capacity_mut()
3247                        .as_mut_ptr()
3248                        .cast::<T>()
3249                        .cast_uninit()
3250                        .cast_array::<N>()
3251                        .as_mut_unchecked();
3252                    let written = then(spare);
3253                    bytes.set_len(old_len + written);
3254                }
3255            }
3256
3257            for c in middle {
3258                match c {
3259                    '\'' | '\"' | '\\' => {
3260                        self.push('\\');
3261                        self.push(c);
3262                    }
3263                    '\x20'..='\x7e' => self.push(c),
3264                    '\t' => {
3265                        self.push('\\');
3266                        self.push('t');
3267                    }
3268                    '\r' => {
3269                        self.push('\\');
3270                        self.push('r');
3271                    }
3272                    '\n' => {
3273                        self.push('\\');
3274                        self.push('n');
3275                    }
3276                    c => {
3277                        // SAFETY: We only let the function write ascii chars, so it remains valid utf8.
3278                        // and it returns the number of bytes written, so so with_spare ensures the rest for us.
3279                        unsafe {
3280                            with_spare::<10, ascii::Char>(self.as_mut_vec(), |spare| {
3281                                escape_unicode_into(spare, c)
3282                            });
3283                        }
3284                    }
3285                }
3286            }
3287        }
3288
3289        if let Some(tail) = tail {
3290            self.extend(tail);
3291        }
3292    }
3293}
3294
3295#[cfg(not(no_global_oom_handling))]
3296#[inline]
3297// adapted from core::escape::escape_unicode, but it's left-aligned instead of right-aligned.
3298fn escape_unicode_into(output: &mut [MaybeUninit<ascii::Char>; 10], c: char) -> usize {
3299    const HEX_DIGITS: [ascii::Char; 16] = *b"0123456789abcdef".as_ascii().unwrap();
3300
3301    let c = c as u32;
3302    // OR-ing `1` ensures that for `c == 0` the code computes that
3303    // one digit should be printed.
3304    let prefix_skip = (c | 1).leading_zeros() as usize / 4 - 2;
3305
3306    // Always write all digits, but for shorter representations the unused
3307    // digits get overwritten by later writes.
3308    output[3usize.saturating_sub(prefix_skip)].write(HEX_DIGITS[((c >> 20) & 15) as usize]);
3309    output[4usize.saturating_sub(prefix_skip)].write(HEX_DIGITS[((c >> 16) & 15) as usize]);
3310    output[5usize.saturating_sub(prefix_skip)].write(HEX_DIGITS[((c >> 12) & 15) as usize]);
3311    output[6usize.saturating_sub(prefix_skip)].write(HEX_DIGITS[((c >> 8) & 15) as usize]);
3312    output[7usize.saturating_sub(prefix_skip)].write(HEX_DIGITS[((c >> 4) & 15) as usize]);
3313    output[8usize.saturating_sub(prefix_skip)].write(HEX_DIGITS[(c & 15) as usize]);
3314
3315    output[0].write(ascii::Char::ReverseSolidus);
3316    output[1].write(ascii::Char::SmallU);
3317    output[2].write(ascii::Char::LeftCurlyBracket);
3318    output[9 - prefix_skip].write(ascii::Char::RightCurlyBracket);
3319
3320    10 - prefix_skip
3321}
3322
3323#[stable(feature = "rust1", since = "1.0.0")]
3324impl AsRef<str> for String {
3325    #[inline]
3326    fn as_ref(&self) -> &str {
3327        self
3328    }
3329}
3330
3331#[stable(feature = "string_as_mut", since = "1.43.0")]
3332impl AsMut<str> for String {
3333    #[inline]
3334    fn as_mut(&mut self) -> &mut str {
3335        self
3336    }
3337}
3338
3339#[stable(feature = "rust1", since = "1.0.0")]
3340impl AsRef<[u8]> for String {
3341    #[inline]
3342    fn as_ref(&self) -> &[u8] {
3343        self.as_bytes()
3344    }
3345}
3346
3347#[cfg(not(no_global_oom_handling))]
3348#[stable(feature = "rust1", since = "1.0.0")]
3349impl From<&str> for String {
3350    /// Converts a `&str` into a [`String`].
3351    ///
3352    /// The result is allocated on the heap.
3353    #[inline]
3354    fn from(s: &str) -> String {
3355        s.to_owned()
3356    }
3357}
3358
3359#[cfg(not(no_global_oom_handling))]
3360#[stable(feature = "from_mut_str_for_string", since = "1.44.0")]
3361impl From<&mut str> for String {
3362    /// Converts a `&mut str` into a [`String`].
3363    ///
3364    /// The result is allocated on the heap.
3365    #[inline]
3366    fn from(s: &mut str) -> String {
3367        s.to_owned()
3368    }
3369}
3370
3371#[cfg(not(no_global_oom_handling))]
3372#[stable(feature = "from_ref_string", since = "1.35.0")]
3373impl From<&String> for String {
3374    /// Converts a `&String` into a [`String`].
3375    ///
3376    /// This clones `s` and returns the clone.
3377    #[inline]
3378    fn from(s: &String) -> String {
3379        s.clone()
3380    }
3381}
3382
3383// note: test pulls in std, which causes errors here
3384#[stable(feature = "string_from_box", since = "1.18.0")]
3385impl From<Box<str>> for String {
3386    /// Converts the given boxed `str` slice to a [`String`].
3387    /// It is notable that the `str` slice is owned.
3388    ///
3389    /// # Examples
3390    ///
3391    /// ```
3392    /// let s1: String = String::from("hello world");
3393    /// let s2: Box<str> = s1.into_boxed_str();
3394    /// let s3: String = String::from(s2);
3395    ///
3396    /// assert_eq!("hello world", s3)
3397    /// ```
3398    fn from(s: Box<str>) -> String {
3399        s.into_string()
3400    }
3401}
3402
3403#[cfg(not(no_global_oom_handling))]
3404#[stable(feature = "box_from_str", since = "1.20.0")]
3405impl From<String> for Box<str> {
3406    /// Converts the given [`String`] to a boxed `str` slice that is owned.
3407    ///
3408    /// # Examples
3409    ///
3410    /// ```
3411    /// let s1: String = String::from("hello world");
3412    /// let s2: Box<str> = Box::from(s1);
3413    /// let s3: String = String::from(s2);
3414    ///
3415    /// assert_eq!("hello world", s3)
3416    /// ```
3417    fn from(s: String) -> Box<str> {
3418        s.into_boxed_str()
3419    }
3420}
3421
3422#[cfg(not(no_global_oom_handling))]
3423#[stable(feature = "string_from_cow_str", since = "1.14.0")]
3424impl<'a> From<Cow<'a, str>> for String {
3425    /// Converts a clone-on-write string to an owned
3426    /// instance of [`String`].
3427    ///
3428    /// This extracts the owned string,
3429    /// clones the string if it is not already owned.
3430    ///
3431    /// # Example
3432    ///
3433    /// ```
3434    /// # use std::borrow::Cow;
3435    /// // If the string is not owned...
3436    /// let cow: Cow<'_, str> = Cow::Borrowed("eggplant");
3437    /// // It will allocate on the heap and copy the string.
3438    /// let owned: String = String::from(cow);
3439    /// assert_eq!(&owned[..], "eggplant");
3440    /// ```
3441    fn from(s: Cow<'a, str>) -> String {
3442        s.into_owned()
3443    }
3444}
3445
3446#[cfg(not(no_global_oom_handling))]
3447#[stable(feature = "rust1", since = "1.0.0")]
3448impl<'a> From<&'a str> for Cow<'a, str> {
3449    /// Converts a string slice into a [`Borrowed`] variant.
3450    /// No heap allocation is performed, and the string
3451    /// is not copied.
3452    ///
3453    /// # Example
3454    ///
3455    /// ```
3456    /// # use std::borrow::Cow;
3457    /// assert_eq!(Cow::from("eggplant"), Cow::Borrowed("eggplant"));
3458    /// ```
3459    ///
3460    /// [`Borrowed`]: crate::borrow::Cow::Borrowed "borrow::Cow::Borrowed"
3461    #[inline]
3462    fn from(s: &'a str) -> Cow<'a, str> {
3463        Cow::Borrowed(s)
3464    }
3465}
3466
3467#[cfg(not(no_global_oom_handling))]
3468#[stable(feature = "rust1", since = "1.0.0")]
3469impl<'a> From<String> for Cow<'a, str> {
3470    /// Converts a [`String`] into an [`Owned`] variant.
3471    /// No heap allocation is performed, and the string
3472    /// is not copied.
3473    ///
3474    /// # Example
3475    ///
3476    /// ```
3477    /// # use std::borrow::Cow;
3478    /// let s = "eggplant".to_string();
3479    /// let s2 = "eggplant".to_string();
3480    /// assert_eq!(Cow::from(s), Cow::<'static, str>::Owned(s2));
3481    /// ```
3482    ///
3483    /// [`Owned`]: crate::borrow::Cow::Owned "borrow::Cow::Owned"
3484    #[inline]
3485    fn from(s: String) -> Cow<'a, str> {
3486        Cow::Owned(s)
3487    }
3488}
3489
3490#[cfg(not(no_global_oom_handling))]
3491#[stable(feature = "cow_from_string_ref", since = "1.28.0")]
3492impl<'a> From<&'a String> for Cow<'a, str> {
3493    /// Converts a [`String`] reference into a [`Borrowed`] variant.
3494    /// No heap allocation is performed, and the string
3495    /// is not copied.
3496    ///
3497    /// # Example
3498    ///
3499    /// ```
3500    /// # use std::borrow::Cow;
3501    /// let s = "eggplant".to_string();
3502    /// assert_eq!(Cow::from(&s), Cow::Borrowed("eggplant"));
3503    /// ```
3504    ///
3505    /// [`Borrowed`]: crate::borrow::Cow::Borrowed "borrow::Cow::Borrowed"
3506    #[inline]
3507    fn from(s: &'a String) -> Cow<'a, str> {
3508        Cow::Borrowed(s.as_str())
3509    }
3510}
3511
3512#[cfg(not(no_global_oom_handling))]
3513#[stable(feature = "cow_str_from_iter", since = "1.12.0")]
3514impl<'a> FromIterator<char> for Cow<'a, str> {
3515    fn from_iter<I: IntoIterator<Item = char>>(it: I) -> Cow<'a, str> {
3516        Cow::Owned(FromIterator::from_iter(it))
3517    }
3518}
3519
3520#[cfg(not(no_global_oom_handling))]
3521#[stable(feature = "cow_str_from_iter", since = "1.12.0")]
3522impl<'a, 'b> FromIterator<&'b str> for Cow<'a, str> {
3523    fn from_iter<I: IntoIterator<Item = &'b str>>(it: I) -> Cow<'a, str> {
3524        Cow::Owned(FromIterator::from_iter(it))
3525    }
3526}
3527
3528#[cfg(not(no_global_oom_handling))]
3529#[stable(feature = "cow_str_from_iter", since = "1.12.0")]
3530impl<'a> FromIterator<String> for Cow<'a, str> {
3531    fn from_iter<I: IntoIterator<Item = String>>(it: I) -> Cow<'a, str> {
3532        Cow::Owned(FromIterator::from_iter(it))
3533    }
3534}
3535
3536#[cfg(not(no_global_oom_handling))]
3537#[unstable(feature = "ascii_char", issue = "110998")]
3538impl<'a> FromIterator<core::ascii::Char> for Cow<'a, str> {
3539    fn from_iter<I: IntoIterator<Item = core::ascii::Char>>(it: I) -> Self {
3540        Cow::Owned(FromIterator::from_iter(it))
3541    }
3542}
3543
3544#[stable(feature = "from_string_for_vec_u8", since = "1.14.0")]
3545impl From<String> for Vec<u8> {
3546    /// Converts the given [`String`] to a vector [`Vec`] that holds values of type [`u8`].
3547    ///
3548    /// # Examples
3549    ///
3550    /// ```
3551    /// let s1 = String::from("hello world");
3552    /// let v1 = Vec::from(s1);
3553    ///
3554    /// for b in v1 {
3555    ///     println!("{b}");
3556    /// }
3557    /// ```
3558    fn from(string: String) -> Vec<u8> {
3559        string.into_bytes()
3560    }
3561}
3562
3563#[stable(feature = "try_from_vec_u8_for_string", since = "1.87.0")]
3564impl TryFrom<Vec<u8>> for String {
3565    type Error = FromUtf8Error;
3566    /// Converts the given [`Vec<u8>`] into a  [`String`] if it contains valid UTF-8 data.
3567    ///
3568    /// # Examples
3569    ///
3570    /// ```
3571    /// let s1 = b"hello world".to_vec();
3572    /// let v1 = String::try_from(s1).unwrap();
3573    /// assert_eq!(v1, "hello world");
3574    ///
3575    /// ```
3576    fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
3577        Self::from_utf8(bytes)
3578    }
3579}
3580
3581/// Note that all methods of this trait append to the `String`'s existing
3582/// contents; they never truncate or replace what is already there. In
3583/// particular, [`fmt::Write::write_str`] uses [`push_str`][String::push_str]
3584/// and [`fmt::Write::write_char`] uses [`push`][String::push].
3585#[cfg(not(no_global_oom_handling))]
3586#[stable(feature = "rust1", since = "1.0.0")]
3587impl fmt::Write for String {
3588    #[inline]
3589    fn write_str(&mut self, s: &str) -> fmt::Result {
3590        self.push_str(s);
3591        Ok(())
3592    }
3593
3594    #[inline]
3595    fn write_char(&mut self, c: char) -> fmt::Result {
3596        self.push(c);
3597        Ok(())
3598    }
3599}
3600
3601/// An iterator over the [`char`]s of a string.
3602///
3603/// This struct is created by the [`into_chars`] method on [`String`].
3604/// See its documentation for more.
3605///
3606/// [`char`]: prim@char
3607/// [`into_chars`]: String::into_chars
3608#[cfg_attr(not(no_global_oom_handling), derive(Clone))]
3609#[must_use = "iterators are lazy and do nothing unless consumed"]
3610#[stable(feature = "string_into_chars", since = "1.101.0")]
3611pub struct IntoChars {
3612    bytes: vec::IntoIter<u8>,
3613}
3614
3615#[stable(feature = "string_into_chars", since = "1.101.0")]
3616impl fmt::Debug for IntoChars {
3617    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3618        f.debug_tuple("IntoChars").field(&self.as_str()).finish()
3619    }
3620}
3621
3622impl IntoChars {
3623    /// Views the underlying data as a subslice of the original data.
3624    ///
3625    /// # Examples
3626    ///
3627    /// ```
3628    /// let mut chars = String::from("abc").into_chars();
3629    ///
3630    /// assert_eq!(chars.as_str(), "abc");
3631    /// chars.next();
3632    /// assert_eq!(chars.as_str(), "bc");
3633    /// chars.next();
3634    /// chars.next();
3635    /// assert_eq!(chars.as_str(), "");
3636    /// ```
3637    #[stable(feature = "string_into_chars", since = "1.101.0")]
3638    #[must_use]
3639    #[inline]
3640    pub fn as_str(&self) -> &str {
3641        // SAFETY: `bytes` is a valid UTF-8 string.
3642        unsafe { str::from_utf8_unchecked(self.bytes.as_slice()) }
3643    }
3644
3645    /// Consumes the `IntoChars`, returning the remaining string.
3646    ///
3647    /// # Examples
3648    ///
3649    /// ```
3650    /// let chars = String::from("abc").into_chars();
3651    /// assert_eq!(chars.into_string(), "abc");
3652    ///
3653    /// let mut chars = String::from("def").into_chars();
3654    /// chars.next();
3655    /// assert_eq!(chars.into_string(), "ef");
3656    /// ```
3657    #[cfg(not(no_global_oom_handling))]
3658    #[stable(feature = "string_into_chars", since = "1.101.0")]
3659    #[inline]
3660    pub fn into_string(self) -> String {
3661        // SAFETY: `bytes` are kept in UTF-8 form, only removing whole `char`s at a time.
3662        unsafe { String::from_utf8_unchecked(self.bytes.collect()) }
3663    }
3664
3665    #[inline]
3666    fn iter(&self) -> CharIndices<'_> {
3667        self.as_str().char_indices()
3668    }
3669}
3670
3671#[stable(feature = "string_into_chars", since = "1.101.0")]
3672impl Iterator for IntoChars {
3673    type Item = char;
3674
3675    #[inline]
3676    fn next(&mut self) -> Option<char> {
3677        let mut iter = self.iter();
3678        match iter.next() {
3679            None => None,
3680            Some((_, ch)) => {
3681                let offset = iter.offset();
3682                // `offset` is a valid index.
3683                let _ = self.bytes.advance_by(offset);
3684                Some(ch)
3685            }
3686        }
3687    }
3688
3689    #[inline]
3690    fn count(self) -> usize {
3691        self.iter().count()
3692    }
3693
3694    #[inline]
3695    fn size_hint(&self) -> (usize, Option<usize>) {
3696        self.iter().size_hint()
3697    }
3698
3699    #[inline]
3700    fn last(mut self) -> Option<char> {
3701        self.next_back()
3702    }
3703}
3704
3705#[stable(feature = "string_into_chars", since = "1.101.0")]
3706impl DoubleEndedIterator for IntoChars {
3707    #[inline]
3708    fn next_back(&mut self) -> Option<char> {
3709        let len = self.as_str().len();
3710        let mut iter = self.iter();
3711        match iter.next_back() {
3712            None => None,
3713            Some((idx, ch)) => {
3714                // `idx` is a valid index.
3715                let _ = self.bytes.advance_back_by(len - idx);
3716                Some(ch)
3717            }
3718        }
3719    }
3720}
3721
3722#[stable(feature = "string_into_chars", since = "1.101.0")]
3723impl FusedIterator for IntoChars {}
3724
3725/// A draining iterator for `String`.
3726///
3727/// This struct is created by the [`drain`] method on [`String`]. See its
3728/// documentation for more.
3729///
3730/// [`drain`]: String::drain
3731#[stable(feature = "drain", since = "1.6.0")]
3732pub struct Drain<'a> {
3733    /// Will be used as &'a mut String in the destructor
3734    string: *mut String,
3735    /// Start of part to remove
3736    start: usize,
3737    /// End of part to remove
3738    end: usize,
3739    /// Current remaining range to remove
3740    iter: Chars<'a>,
3741}
3742
3743#[stable(feature = "collection_debug", since = "1.17.0")]
3744impl fmt::Debug for Drain<'_> {
3745    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3746        f.debug_tuple("Drain").field(&self.as_str()).finish()
3747    }
3748}
3749
3750#[stable(feature = "drain", since = "1.6.0")]
3751unsafe impl Sync for Drain<'_> {}
3752#[stable(feature = "drain", since = "1.6.0")]
3753unsafe impl Send for Drain<'_> {}
3754
3755#[stable(feature = "drain", since = "1.6.0")]
3756impl Drop for Drain<'_> {
3757    fn drop(&mut self) {
3758        // Use Vec::drain. "Reaffirm" the bounds checks to avoid
3759        // panic code being inserted again.
3760        // SAFETY: We only use the returned Vec to call drain.
3761        let self_vec = unsafe { &mut *(*self.string).as_mut_vec() };
3762        if self.start <= self.end && self.end <= self_vec.len() {
3763            self_vec.drain(self.start..self.end);
3764        }
3765    }
3766}
3767
3768impl<'a> Drain<'a> {
3769    /// Returns the remaining (sub)string of this iterator as a slice.
3770    ///
3771    /// # Examples
3772    ///
3773    /// ```
3774    /// let mut s = String::from("abc");
3775    /// let mut drain = s.drain(..);
3776    /// assert_eq!(drain.as_str(), "abc");
3777    /// let _ = drain.next().unwrap();
3778    /// assert_eq!(drain.as_str(), "bc");
3779    /// ```
3780    #[must_use]
3781    #[stable(feature = "string_drain_as_str", since = "1.55.0")]
3782    pub fn as_str(&self) -> &str {
3783        self.iter.as_str()
3784    }
3785}
3786
3787#[stable(feature = "string_drain_as_str", since = "1.55.0")]
3788impl<'a> AsRef<str> for Drain<'a> {
3789    fn as_ref(&self) -> &str {
3790        self.as_str()
3791    }
3792}
3793
3794#[stable(feature = "string_drain_as_str", since = "1.55.0")]
3795impl<'a> AsRef<[u8]> for Drain<'a> {
3796    fn as_ref(&self) -> &[u8] {
3797        self.as_str().as_bytes()
3798    }
3799}
3800
3801#[stable(feature = "drain", since = "1.6.0")]
3802impl Iterator for Drain<'_> {
3803    type Item = char;
3804
3805    #[inline]
3806    fn next(&mut self) -> Option<char> {
3807        self.iter.next()
3808    }
3809
3810    fn size_hint(&self) -> (usize, Option<usize>) {
3811        self.iter.size_hint()
3812    }
3813
3814    #[inline]
3815    fn last(mut self) -> Option<char> {
3816        self.next_back()
3817    }
3818}
3819
3820#[stable(feature = "drain", since = "1.6.0")]
3821impl DoubleEndedIterator for Drain<'_> {
3822    #[inline]
3823    fn next_back(&mut self) -> Option<char> {
3824        self.iter.next_back()
3825    }
3826}
3827
3828#[stable(feature = "fused", since = "1.26.0")]
3829impl FusedIterator for Drain<'_> {}
3830
3831#[cfg(not(no_global_oom_handling))]
3832#[stable(feature = "from_char_for_string", since = "1.46.0")]
3833impl From<char> for String {
3834    /// Allocates an owned [`String`] from a single character.
3835    ///
3836    /// # Example
3837    /// ```rust
3838    /// let c: char = 'a';
3839    /// let s: String = String::from(c);
3840    /// assert_eq!("a", &s[..]);
3841    /// ```
3842    #[inline]
3843    fn from(c: char) -> Self {
3844        c.to_string()
3845    }
3846}