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