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