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