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