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