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