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