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