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