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