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