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