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