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