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