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