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