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