1 //! A UTF-8βencoded, growable string.
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.
9 //! There are multiple ways to create a new [`String`] from a string literal:
12 //! let s = "Hello".to_string();
14 //! let s = String::from("world");
15 //! let s: String = "also this".into();
18 //! You can create a new [`String`] from an existing one by concatenating with
22 //! let s = "Hello".to_string();
24 //! let message = s + " world!";
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.
31 //! let sparkle_heart = vec![240, 159, 146, 150];
33 //! // We know these bytes are valid, so we'll use `unwrap()`.
34 //! let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
36 //! assert_eq!("π", sparkle_heart);
38 //! let bytes = sparkle_heart.into_bytes();
40 //! assert_eq!(bytes, [240, 159, 146, 150]);
43 #![stable(feature = "rust1", since = "1.0.0")]
45 #[cfg(not(no_global_oom_handling))]
46 use core::char::{decode_utf16, REPLACEMENT_CHARACTER};
47 #[cfg(not(bootstrap))]
48 use core::error::Error;
51 use core::iter::FusedIterator;
52 #[cfg(not(no_global_oom_handling))]
53 use core::iter::{from_fn, FromIterator};
54 #[cfg(not(no_global_oom_handling))]
56 #[cfg(not(no_global_oom_handling))]
57 use core::ops::AddAssign;
58 #[cfg(not(no_global_oom_handling))]
59 use core::ops::Bound::{Excluded, Included, Unbounded};
60 use core::ops::{self, Index, IndexMut, Range, RangeBounds};
63 use core::str::pattern::Pattern;
64 #[cfg(not(no_global_oom_handling))]
65 use core::str::Utf8Chunks;
67 #[cfg(not(no_global_oom_handling))]
68 use crate::borrow::{Cow, ToOwned};
69 use crate::boxed::Box;
70 use crate::collections::TryReserveError;
71 use crate::str::{self, Chars, Utf8Error};
72 #[cfg(not(no_global_oom_handling))]
73 use crate::str::{from_boxed_utf8_unchecked, FromStr};
76 /// A UTF-8βencoded, growable string.
78 /// The `String` type is the most common string type that has ownership over the
79 /// contents of the string. It has a close relationship with its borrowed
80 /// counterpart, the primitive [`str`].
84 /// You can create a `String` from [a literal string][`&str`] with [`String::from`]:
86 /// [`String::from`]: From::from
89 /// let hello = String::from("Hello, world!");
92 /// You can append a [`char`] to a `String` with the [`push`] method, and
93 /// append a [`&str`] with the [`push_str`] method:
96 /// let mut hello = String::from("Hello, ");
99 /// hello.push_str("orld!");
102 /// [`push`]: String::push
103 /// [`push_str`]: String::push_str
105 /// If you have a vector of UTF-8 bytes, you can create a `String` from it with
106 /// the [`from_utf8`] method:
109 /// // some bytes, in a vector
110 /// let sparkle_heart = vec![240, 159, 146, 150];
112 /// // We know these bytes are valid, so we'll use `unwrap()`.
113 /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
115 /// assert_eq!("π", sparkle_heart);
118 /// [`from_utf8`]: String::from_utf8
122 /// `String`s are always valid UTF-8. If you need a non-UTF-8 string, consider
123 /// [`OsString`]. It is similar, but without the UTF-8 constraint. Because UTF-8
124 /// is a variable width encoding, `String`s are typically smaller than an array of
125 /// the same `chars`:
130 /// // `s` is ASCII which represents each `char` as one byte
132 /// assert_eq!(s.len(), 5);
134 /// // A `char` array with the same contents would be longer because
135 /// // every `char` is four bytes
136 /// let s = ['h', 'e', 'l', 'l', 'o'];
137 /// let size: usize = s.into_iter().map(|c| mem::size_of_val(&c)).sum();
138 /// assert_eq!(size, 20);
140 /// // However, for non-ASCII strings, the difference will be smaller
141 /// // and sometimes they are the same
142 /// let s = "πππππ";
143 /// assert_eq!(s.len(), 20);
145 /// let s = ['π', 'π', 'π', 'π', 'π'];
146 /// let size: usize = s.into_iter().map(|c| mem::size_of_val(&c)).sum();
147 /// assert_eq!(size, 20);
150 /// This raises interesting questions as to how `s[i]` should work.
151 /// What should `i` be here? Several options include byte indices and
152 /// `char` indices but, because of UTF-8 encoding, only byte indices
153 /// would provide constant time indexing. Getting the `i`th `char`, for
154 /// example, is available using [`chars`]:
158 /// let third_character = s.chars().nth(2);
159 /// assert_eq!(third_character, Some('l'));
161 /// let s = "πππππ";
162 /// let third_character = s.chars().nth(2);
163 /// assert_eq!(third_character, Some('π'));
166 /// Next, what should `s[i]` return? Because indexing returns a reference
167 /// to underlying data it could be `&u8`, `&[u8]`, or something else similar.
168 /// Since we're only providing one index, `&u8` makes the most sense but that
169 /// might not be what the user expects and can be explicitly achieved with
173 /// // The first byte is 104 - the byte value of `'h'`
175 /// assert_eq!(s.as_bytes()[0], 104);
177 /// assert_eq!(s.as_bytes()[0], b'h');
179 /// // The first byte is 240 which isn't obviously useful
180 /// let s = "πππππ";
181 /// assert_eq!(s.as_bytes()[0], 240);
184 /// Due to these ambiguities/restrictions, indexing with a `usize` is simply
187 /// ```compile_fail,E0277
190 /// // The following will not compile!
191 /// println!("The first letter of s is {}", s[0]);
194 /// It is more clear, however, how `&s[i..j]` should work (that is,
195 /// indexing with a range). It should accept byte indices (to be constant-time)
196 /// and return a `&str` which is UTF-8 encoded. This is also called "string slicing".
197 /// Note this will panic if the byte indices provided are not character
198 /// boundaries - see [`is_char_boundary`] for more details. See the implementations
199 /// for [`SliceIndex<str>`] for more details on string slicing. For a non-panicking
200 /// version of string slicing, see [`get`].
202 /// [`OsString`]: ../../std/ffi/struct.OsString.html "ffi::OsString"
203 /// [`SliceIndex<str>`]: core::slice::SliceIndex
204 /// [`as_bytes()`]: str::as_bytes
205 /// [`get`]: str::get
206 /// [`is_char_boundary`]: str::is_char_boundary
208 /// The [`bytes`] and [`chars`] methods return iterators over the bytes and
209 /// codepoints of the string, respectively. To iterate over codepoints along
210 /// with byte indices, use [`char_indices`].
212 /// [`bytes`]: str::bytes
213 /// [`chars`]: str::chars
214 /// [`char_indices`]: str::char_indices
218 /// `String` implements <code>[Deref]<Target = [str]></code>, and so inherits all of [`str`]'s
219 /// methods. In addition, this means that you can pass a `String` to a
220 /// function which takes a [`&str`] by using an ampersand (`&`):
223 /// fn takes_str(s: &str) { }
225 /// let s = String::from("Hello");
230 /// This will create a [`&str`] from the `String` and pass it in. This
231 /// conversion is very inexpensive, and so generally, functions will accept
232 /// [`&str`]s as arguments unless they need a `String` for some specific
235 /// In certain cases Rust doesn't have enough information to make this
236 /// conversion, known as [`Deref`] coercion. In the following example a string
237 /// slice [`&'a str`][`&str`] implements the trait `TraitExample`, and the function
238 /// `example_func` takes anything that implements the trait. In this case Rust
239 /// would need to make two implicit conversions, which Rust doesn't have the
240 /// means to do. For that reason, the following example will not compile.
242 /// ```compile_fail,E0277
243 /// trait TraitExample {}
245 /// impl<'a> TraitExample for &'a str {}
247 /// fn example_func<A: TraitExample>(example_arg: A) {}
249 /// let example_string = String::from("example_string");
250 /// example_func(&example_string);
253 /// There are two options that would work instead. The first would be to
254 /// change the line `example_func(&example_string);` to
255 /// `example_func(example_string.as_str());`, using the method [`as_str()`]
256 /// to explicitly extract the string slice containing the string. The second
257 /// way changes `example_func(&example_string);` to
258 /// `example_func(&*example_string);`. In this case we are dereferencing a
259 /// `String` to a [`str`], then referencing the [`str`] back to
260 /// [`&str`]. The second way is more idiomatic, however both work to do the
261 /// conversion explicitly rather than relying on the implicit conversion.
265 /// A `String` is made up of three components: a pointer to some bytes, a
266 /// length, and a capacity. The pointer points to an internal buffer `String`
267 /// uses to store its data. The length is the number of bytes currently stored
268 /// in the buffer, and the capacity is the size of the buffer in bytes. As such,
269 /// the length will always be less than or equal to the capacity.
271 /// This buffer is always stored on the heap.
273 /// You can look at these with the [`as_ptr`], [`len`], and [`capacity`]
279 /// let story = String::from("Once upon a time...");
281 // FIXME Update this when vec_into_raw_parts is stabilized
282 /// // Prevent automatically dropping the String's data
283 /// let mut story = mem::ManuallyDrop::new(story);
285 /// let ptr = story.as_mut_ptr();
286 /// let len = story.len();
287 /// let capacity = story.capacity();
289 /// // story has nineteen bytes
290 /// assert_eq!(19, len);
292 /// // We can re-build a String out of ptr, len, and capacity. This is all
293 /// // unsafe because we are responsible for making sure the components are
295 /// let s = unsafe { String::from_raw_parts(ptr, len, capacity) } ;
297 /// assert_eq!(String::from("Once upon a time..."), s);
300 /// [`as_ptr`]: str::as_ptr
301 /// [`len`]: String::len
302 /// [`capacity`]: String::capacity
304 /// If a `String` has enough capacity, adding elements to it will not
305 /// re-allocate. For example, consider this program:
308 /// let mut s = String::new();
310 /// println!("{}", s.capacity());
313 /// s.push_str("hello");
314 /// println!("{}", s.capacity());
318 /// This will output the following:
329 /// At first, we have no memory allocated at all, but as we append to the
330 /// string, it increases its capacity appropriately. If we instead use the
331 /// [`with_capacity`] method to allocate the correct capacity initially:
334 /// let mut s = String::with_capacity(25);
336 /// println!("{}", s.capacity());
339 /// s.push_str("hello");
340 /// println!("{}", s.capacity());
344 /// [`with_capacity`]: String::with_capacity
346 /// We end up with a different output:
357 /// Here, there's no need to allocate more memory inside the loop.
359 /// [str]: prim@str "str"
360 /// [`str`]: prim@str "str"
361 /// [`&str`]: prim@str "&str"
362 /// [Deref]: core::ops::Deref "ops::Deref"
363 /// [`Deref`]: core::ops::Deref "ops::Deref"
364 /// [`as_str()`]: String::as_str
365 #[derive(PartialOrd, Eq, Ord)]
366 #[cfg_attr(not(test), rustc_diagnostic_item = "String")]
367 #[stable(feature = "rust1", since = "1.0.0")]
372 /// A possible error value when converting a `String` from a UTF-8 byte vector.
374 /// This type is the error type for the [`from_utf8`] method on [`String`]. It
375 /// is designed in such a way to carefully avoid reallocations: the
376 /// [`into_bytes`] method will give back the byte vector that was used in the
377 /// conversion attempt.
379 /// [`from_utf8`]: String::from_utf8
380 /// [`into_bytes`]: FromUtf8Error::into_bytes
382 /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
383 /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
384 /// an analogue to `FromUtf8Error`, and you can get one from a `FromUtf8Error`
385 /// through the [`utf8_error`] method.
387 /// [`Utf8Error`]: str::Utf8Error "std::str::Utf8Error"
388 /// [`std::str`]: core::str "std::str"
389 /// [`&str`]: prim@str "&str"
390 /// [`utf8_error`]: FromUtf8Error::utf8_error
397 /// // some invalid bytes, in a vector
398 /// let bytes = vec![0, 159];
400 /// let value = String::from_utf8(bytes);
402 /// assert!(value.is_err());
403 /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
405 #[stable(feature = "rust1", since = "1.0.0")]
406 #[cfg_attr(not(no_global_oom_handling), derive(Clone))]
407 #[derive(Debug, PartialEq, Eq)]
408 pub struct FromUtf8Error {
413 /// A possible error value when converting a `String` from a UTF-16 byte slice.
415 /// This type is the error type for the [`from_utf16`] method on [`String`].
417 /// [`from_utf16`]: String::from_utf16
423 /// // πmu<invalid>ic
424 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
425 /// 0xD800, 0x0069, 0x0063];
427 /// assert!(String::from_utf16(v).is_err());
429 #[stable(feature = "rust1", since = "1.0.0")]
431 pub struct FromUtf16Error(());
434 /// Creates a new empty `String`.
436 /// Given that the `String` is empty, this will not allocate any initial
437 /// buffer. While that means that this initial operation is very
438 /// inexpensive, it may cause excessive allocation later when you add
439 /// data. If you have an idea of how much data the `String` will hold,
440 /// consider the [`with_capacity`] method to prevent excessive
443 /// [`with_capacity`]: String::with_capacity
450 /// let s = String::new();
453 #[rustc_const_stable(feature = "const_string_new", since = "1.39.0")]
454 #[stable(feature = "rust1", since = "1.0.0")]
456 pub const fn new() -> String {
457 String { vec: Vec::new() }
460 /// Creates a new empty `String` with at least the specified capacity.
462 /// `String`s have an internal buffer to hold their data. The capacity is
463 /// the length of that buffer, and can be queried with the [`capacity`]
464 /// method. This method creates an empty `String`, but one with an initial
465 /// buffer that can hold at least `capacity` bytes. This is useful when you
466 /// may be appending a bunch of data to the `String`, reducing the number of
467 /// reallocations it needs to do.
469 /// [`capacity`]: String::capacity
471 /// If the given capacity is `0`, no allocation will occur, and this method
472 /// is identical to the [`new`] method.
474 /// [`new`]: String::new
481 /// let mut s = String::with_capacity(10);
483 /// // The String contains no chars, even though it has capacity for more
484 /// assert_eq!(s.len(), 0);
486 /// // These are all done without reallocating...
487 /// let cap = s.capacity();
492 /// assert_eq!(s.capacity(), cap);
494 /// // ...but this may make the string reallocate
497 #[cfg(not(no_global_oom_handling))]
499 #[stable(feature = "rust1", since = "1.0.0")]
501 pub fn with_capacity(capacity: usize) -> String {
502 String { vec: Vec::with_capacity(capacity) }
505 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
506 // required for this method definition, is not available. Since we don't
507 // require this method for testing purposes, I'll just stub it
508 // NB see the slice::hack module in slice.rs for more information
511 pub fn from_str(_: &str) -> String {
512 panic!("not available with cfg(test)");
515 /// Converts a vector of bytes to a `String`.
517 /// A string ([`String`]) is made of bytes ([`u8`]), and a vector of bytes
518 /// ([`Vec<u8>`]) is made of bytes, so this function converts between the
519 /// two. Not all byte slices are valid `String`s, however: `String`
520 /// requires that it is valid UTF-8. `from_utf8()` checks to ensure that
521 /// the bytes are valid UTF-8, and then does the conversion.
523 /// If you are sure that the byte slice is valid UTF-8, and you don't want
524 /// to incur the overhead of the validity check, there is an unsafe version
525 /// of this function, [`from_utf8_unchecked`], which has the same behavior
526 /// but skips the check.
528 /// This method will take care to not copy the vector, for efficiency's
531 /// If you need a [`&str`] instead of a `String`, consider
532 /// [`str::from_utf8`].
534 /// The inverse of this method is [`into_bytes`].
538 /// Returns [`Err`] if the slice is not UTF-8 with a description as to why the
539 /// provided bytes are not UTF-8. The vector you moved in is also included.
546 /// // some bytes, in a vector
547 /// let sparkle_heart = vec![240, 159, 146, 150];
549 /// // We know these bytes are valid, so we'll use `unwrap()`.
550 /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
552 /// assert_eq!("π", sparkle_heart);
558 /// // some invalid bytes, in a vector
559 /// let sparkle_heart = vec![0, 159, 146, 150];
561 /// assert!(String::from_utf8(sparkle_heart).is_err());
564 /// See the docs for [`FromUtf8Error`] for more details on what you can do
567 /// [`from_utf8_unchecked`]: String::from_utf8_unchecked
568 /// [`Vec<u8>`]: crate::vec::Vec "Vec"
569 /// [`&str`]: prim@str "&str"
570 /// [`into_bytes`]: String::into_bytes
572 #[stable(feature = "rust1", since = "1.0.0")]
573 pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error> {
574 match str::from_utf8(&vec) {
575 Ok(..) => Ok(String { vec }),
576 Err(e) => Err(FromUtf8Error { bytes: vec, error: e }),
580 /// Converts a slice of bytes to a string, including invalid characters.
582 /// Strings are made of bytes ([`u8`]), and a slice of bytes
583 /// ([`&[u8]`][byteslice]) is made of bytes, so this function converts
584 /// between the two. Not all byte slices are valid strings, however: strings
585 /// are required to be valid UTF-8. During this conversion,
586 /// `from_utf8_lossy()` will replace any invalid UTF-8 sequences with
587 /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD], which looks like this: οΏ½
589 /// [byteslice]: prim@slice
590 /// [U+FFFD]: core::char::REPLACEMENT_CHARACTER
592 /// If you are sure that the byte slice is valid UTF-8, and you don't want
593 /// to incur the overhead of the conversion, there is an unsafe version
594 /// of this function, [`from_utf8_unchecked`], which has the same behavior
595 /// but skips the checks.
597 /// [`from_utf8_unchecked`]: String::from_utf8_unchecked
599 /// This function returns a [`Cow<'a, str>`]. If our byte slice is invalid
600 /// UTF-8, then we need to insert the replacement characters, which will
601 /// change the size of the string, and hence, require a `String`. But if
602 /// it's already valid UTF-8, we don't need a new allocation. This return
603 /// type allows us to handle both cases.
605 /// [`Cow<'a, str>`]: crate::borrow::Cow "borrow::Cow"
612 /// // some bytes, in a vector
613 /// let sparkle_heart = vec![240, 159, 146, 150];
615 /// let sparkle_heart = String::from_utf8_lossy(&sparkle_heart);
617 /// assert_eq!("π", sparkle_heart);
623 /// // some invalid bytes
624 /// let input = b"Hello \xF0\x90\x80World";
625 /// let output = String::from_utf8_lossy(input);
627 /// assert_eq!("Hello οΏ½World", output);
630 #[cfg(not(no_global_oom_handling))]
631 #[stable(feature = "rust1", since = "1.0.0")]
632 pub fn from_utf8_lossy(v: &[u8]) -> Cow<'_, str> {
633 let mut iter = Utf8Chunks::new(v);
635 let first_valid = if let Some(chunk) = iter.next() {
636 let valid = chunk.valid();
637 if chunk.invalid().is_empty() {
638 debug_assert_eq!(valid.len(), v.len());
639 return Cow::Borrowed(valid);
643 return Cow::Borrowed("");
646 const REPLACEMENT: &str = "\u{FFFD}";
648 let mut res = String::with_capacity(v.len());
649 res.push_str(first_valid);
650 res.push_str(REPLACEMENT);
653 res.push_str(chunk.valid());
654 if !chunk.invalid().is_empty() {
655 res.push_str(REPLACEMENT);
662 /// Decode a UTF-16βencoded vector `v` into a `String`, returning [`Err`]
663 /// if `v` contains any invalid data.
671 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
672 /// 0x0073, 0x0069, 0x0063];
673 /// assert_eq!(String::from("πmusic"),
674 /// String::from_utf16(v).unwrap());
676 /// // πmu<invalid>ic
677 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
678 /// 0xD800, 0x0069, 0x0063];
679 /// assert!(String::from_utf16(v).is_err());
681 #[cfg(not(no_global_oom_handling))]
682 #[stable(feature = "rust1", since = "1.0.0")]
683 pub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error> {
684 // This isn't done via collect::<Result<_, _>>() for performance reasons.
685 // FIXME: the function can be simplified again when #48994 is closed.
686 let mut ret = String::with_capacity(v.len());
687 for c in decode_utf16(v.iter().cloned()) {
691 return Err(FromUtf16Error(()));
697 /// Decode a UTF-16βencoded slice `v` into a `String`, replacing
698 /// invalid data with [the replacement character (`U+FFFD`)][U+FFFD].
700 /// Unlike [`from_utf8_lossy`] which returns a [`Cow<'a, str>`],
701 /// `from_utf16_lossy` returns a `String` since the UTF-16 to UTF-8
702 /// conversion requires a memory allocation.
704 /// [`from_utf8_lossy`]: String::from_utf8_lossy
705 /// [`Cow<'a, str>`]: crate::borrow::Cow "borrow::Cow"
706 /// [U+FFFD]: core::char::REPLACEMENT_CHARACTER
713 /// // πmus<invalid>ic<invalid>
714 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
715 /// 0x0073, 0xDD1E, 0x0069, 0x0063,
718 /// assert_eq!(String::from("πmus\u{FFFD}ic\u{FFFD}"),
719 /// String::from_utf16_lossy(v));
721 #[cfg(not(no_global_oom_handling))]
724 #[stable(feature = "rust1", since = "1.0.0")]
725 pub fn from_utf16_lossy(v: &[u16]) -> String {
726 decode_utf16(v.iter().cloned()).map(|r| r.unwrap_or(REPLACEMENT_CHARACTER)).collect()
729 /// Decomposes a `String` into its raw components.
731 /// Returns the raw pointer to the underlying data, the length of
732 /// the string (in bytes), and the allocated capacity of the data
733 /// (in bytes). These are the same arguments in the same order as
734 /// the arguments to [`from_raw_parts`].
736 /// After calling this function, the caller is responsible for the
737 /// memory previously managed by the `String`. The only way to do
738 /// this is to convert the raw pointer, length, and capacity back
739 /// into a `String` with the [`from_raw_parts`] function, allowing
740 /// the destructor to perform the cleanup.
742 /// [`from_raw_parts`]: String::from_raw_parts
747 /// #![feature(vec_into_raw_parts)]
748 /// let s = String::from("hello");
750 /// let (ptr, len, cap) = s.into_raw_parts();
752 /// let rebuilt = unsafe { String::from_raw_parts(ptr, len, cap) };
753 /// assert_eq!(rebuilt, "hello");
755 #[must_use = "`self` will be dropped if the result is not used"]
756 #[unstable(feature = "vec_into_raw_parts", reason = "new API", issue = "65816")]
757 pub fn into_raw_parts(self) -> (*mut u8, usize, usize) {
758 self.vec.into_raw_parts()
761 /// Creates a new `String` from a length, capacity, and pointer.
765 /// This is highly unsafe, due to the number of invariants that aren't
768 /// * The memory at `buf` needs to have been previously allocated by the
769 /// same allocator the standard library uses, with a required alignment of exactly 1.
770 /// * `length` needs to be less than or equal to `capacity`.
771 /// * `capacity` needs to be the correct value.
772 /// * The first `length` bytes at `buf` need to be valid UTF-8.
774 /// Violating these may cause problems like corrupting the allocator's
775 /// internal data structures. For example, it is normally **not** safe to
776 /// build a `String` from a pointer to a C `char` array containing UTF-8
777 /// _unless_ you are certain that array was originally allocated by the
778 /// Rust standard library's allocator.
780 /// The ownership of `buf` is effectively transferred to the
781 /// `String` which may then deallocate, reallocate or change the
782 /// contents of memory pointed to by the pointer at will. Ensure
783 /// that nothing else uses the pointer after calling this
794 /// let s = String::from("hello");
796 // FIXME Update this when vec_into_raw_parts is stabilized
797 /// // Prevent automatically dropping the String's data
798 /// let mut s = mem::ManuallyDrop::new(s);
800 /// let ptr = s.as_mut_ptr();
801 /// let len = s.len();
802 /// let capacity = s.capacity();
804 /// let s = String::from_raw_parts(ptr, len, capacity);
806 /// assert_eq!(String::from("hello"), s);
810 #[stable(feature = "rust1", since = "1.0.0")]
811 pub unsafe fn from_raw_parts(buf: *mut u8, length: usize, capacity: usize) -> String {
812 unsafe { String { vec: Vec::from_raw_parts(buf, length, capacity) } }
815 /// Converts a vector of bytes to a `String` without checking that the
816 /// string contains valid UTF-8.
818 /// See the safe version, [`from_utf8`], for more details.
820 /// [`from_utf8`]: String::from_utf8
824 /// This function is unsafe because it does not check that the bytes passed
825 /// to it are valid UTF-8. If this constraint is violated, it may cause
826 /// memory unsafety issues with future users of the `String`, as the rest of
827 /// the standard library assumes that `String`s are valid UTF-8.
834 /// // some bytes, in a vector
835 /// let sparkle_heart = vec![240, 159, 146, 150];
837 /// let sparkle_heart = unsafe {
838 /// String::from_utf8_unchecked(sparkle_heart)
841 /// assert_eq!("π", sparkle_heart);
845 #[stable(feature = "rust1", since = "1.0.0")]
846 pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String {
847 String { vec: bytes }
850 /// Converts a `String` into a byte vector.
852 /// This consumes the `String`, so we do not need to copy its contents.
859 /// let s = String::from("hello");
860 /// let bytes = s.into_bytes();
862 /// assert_eq!(&[104, 101, 108, 108, 111][..], &bytes[..]);
865 #[must_use = "`self` will be dropped if the result is not used"]
866 #[stable(feature = "rust1", since = "1.0.0")]
867 pub fn into_bytes(self) -> Vec<u8> {
871 /// Extracts a string slice containing the entire `String`.
878 /// let s = String::from("foo");
880 /// assert_eq!("foo", s.as_str());
884 #[stable(feature = "string_as_str", since = "1.7.0")]
885 pub fn as_str(&self) -> &str {
889 /// Converts a `String` into a mutable string slice.
896 /// let mut s = String::from("foobar");
897 /// let s_mut_str = s.as_mut_str();
899 /// s_mut_str.make_ascii_uppercase();
901 /// assert_eq!("FOOBAR", s_mut_str);
905 #[stable(feature = "string_as_str", since = "1.7.0")]
906 pub fn as_mut_str(&mut self) -> &mut str {
910 /// Appends a given string slice onto the end of this `String`.
917 /// let mut s = String::from("foo");
919 /// s.push_str("bar");
921 /// assert_eq!("foobar", s);
923 #[cfg(not(no_global_oom_handling))]
925 #[stable(feature = "rust1", since = "1.0.0")]
926 pub fn push_str(&mut self, string: &str) {
927 self.vec.extend_from_slice(string.as_bytes())
930 /// Copies elements from `src` range to the end of the string.
934 /// Panics if the starting point or end point do not lie on a [`char`]
935 /// boundary, or if they're out of bounds.
940 /// #![feature(string_extend_from_within)]
941 /// let mut string = String::from("abcde");
943 /// string.extend_from_within(2..);
944 /// assert_eq!(string, "abcdecde");
946 /// string.extend_from_within(..2);
947 /// assert_eq!(string, "abcdecdeab");
949 /// string.extend_from_within(4..8);
950 /// assert_eq!(string, "abcdecdeabecde");
952 #[cfg(not(no_global_oom_handling))]
953 #[unstable(feature = "string_extend_from_within", issue = "none")]
954 pub fn extend_from_within<R>(&mut self, src: R)
956 R: RangeBounds<usize>,
958 let src @ Range { start, end } = slice::range(src, ..self.len());
960 assert!(self.is_char_boundary(start));
961 assert!(self.is_char_boundary(end));
963 self.vec.extend_from_within(src);
966 /// Returns this `String`'s capacity, in bytes.
973 /// let s = String::with_capacity(10);
975 /// assert!(s.capacity() >= 10);
979 #[stable(feature = "rust1", since = "1.0.0")]
980 pub fn capacity(&self) -> usize {
984 /// Reserves capacity for at least `additional` bytes more than the
985 /// current length. The allocator may reserve more space to speculatively
986 /// avoid frequent allocations. After calling `reserve`,
987 /// capacity will be greater than or equal to `self.len() + additional`.
988 /// Does nothing if capacity is already sufficient.
992 /// Panics if the new capacity overflows [`usize`].
999 /// let mut s = String::new();
1003 /// assert!(s.capacity() >= 10);
1006 /// This might not actually increase the capacity:
1009 /// let mut s = String::with_capacity(10);
1013 /// // s now has a length of 2 and a capacity of at least 10
1014 /// let capacity = s.capacity();
1015 /// assert_eq!(2, s.len());
1016 /// assert!(capacity >= 10);
1018 /// // Since we already have at least an extra 8 capacity, calling this...
1021 /// // ... doesn't actually increase.
1022 /// assert_eq!(capacity, s.capacity());
1024 #[cfg(not(no_global_oom_handling))]
1026 #[stable(feature = "rust1", since = "1.0.0")]
1027 pub fn reserve(&mut self, additional: usize) {
1028 self.vec.reserve(additional)
1031 /// Reserves the minimum capacity for at least `additional` bytes more than
1032 /// the current length. Unlike [`reserve`], this will not
1033 /// deliberately over-allocate to speculatively avoid frequent allocations.
1034 /// After calling `reserve_exact`, capacity will be greater than or equal to
1035 /// `self.len() + additional`. Does nothing if the capacity is already
1038 /// [`reserve`]: String::reserve
1042 /// Panics if the new capacity overflows [`usize`].
1049 /// let mut s = String::new();
1051 /// s.reserve_exact(10);
1053 /// assert!(s.capacity() >= 10);
1056 /// This might not actually increase the capacity:
1059 /// let mut s = String::with_capacity(10);
1063 /// // s now has a length of 2 and a capacity of at least 10
1064 /// let capacity = s.capacity();
1065 /// assert_eq!(2, s.len());
1066 /// assert!(capacity >= 10);
1068 /// // Since we already have at least an extra 8 capacity, calling this...
1069 /// s.reserve_exact(8);
1071 /// // ... doesn't actually increase.
1072 /// assert_eq!(capacity, s.capacity());
1074 #[cfg(not(no_global_oom_handling))]
1076 #[stable(feature = "rust1", since = "1.0.0")]
1077 pub fn reserve_exact(&mut self, additional: usize) {
1078 self.vec.reserve_exact(additional)
1081 /// Tries to reserve capacity for at least `additional` bytes more than the
1082 /// current length. The allocator may reserve more space to speculatively
1083 /// avoid frequent allocations. After calling `try_reserve`, capacity will be
1084 /// greater than or equal to `self.len() + additional` if it returns
1085 /// `Ok(())`. Does nothing if capacity is already sufficient. This method
1086 /// preserves the contents even if an error occurs.
1090 /// If the capacity overflows, or the allocator reports a failure, then an error
1096 /// use std::collections::TryReserveError;
1098 /// fn process_data(data: &str) -> Result<String, TryReserveError> {
1099 /// let mut output = String::new();
1101 /// // Pre-reserve the memory, exiting if we can't
1102 /// output.try_reserve(data.len())?;
1104 /// // Now we know this can't OOM in the middle of our complex work
1105 /// output.push_str(data);
1109 /// # process_data("rust").expect("why is the test harness OOMing on 4 bytes?");
1111 #[stable(feature = "try_reserve", since = "1.57.0")]
1112 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
1113 self.vec.try_reserve(additional)
1116 /// Tries to reserve the minimum capacity for at least `additional` bytes
1117 /// more than the current length. Unlike [`try_reserve`], this will not
1118 /// deliberately over-allocate to speculatively avoid frequent allocations.
1119 /// After calling `try_reserve_exact`, capacity will be greater than or
1120 /// equal to `self.len() + additional` if it returns `Ok(())`.
1121 /// Does nothing if the capacity is already sufficient.
1123 /// Note that the allocator may give the collection more space than it
1124 /// requests. Therefore, capacity can not be relied upon to be precisely
1125 /// minimal. Prefer [`try_reserve`] if future insertions are expected.
1127 /// [`try_reserve`]: String::try_reserve
1131 /// If the capacity overflows, or the allocator reports a failure, then an error
1137 /// use std::collections::TryReserveError;
1139 /// fn process_data(data: &str) -> Result<String, TryReserveError> {
1140 /// let mut output = String::new();
1142 /// // Pre-reserve the memory, exiting if we can't
1143 /// output.try_reserve_exact(data.len())?;
1145 /// // Now we know this can't OOM in the middle of our complex work
1146 /// output.push_str(data);
1150 /// # process_data("rust").expect("why is the test harness OOMing on 4 bytes?");
1152 #[stable(feature = "try_reserve", since = "1.57.0")]
1153 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
1154 self.vec.try_reserve_exact(additional)
1157 /// Shrinks the capacity of this `String` to match its length.
1164 /// let mut s = String::from("foo");
1167 /// assert!(s.capacity() >= 100);
1169 /// s.shrink_to_fit();
1170 /// assert_eq!(3, s.capacity());
1172 #[cfg(not(no_global_oom_handling))]
1174 #[stable(feature = "rust1", since = "1.0.0")]
1175 pub fn shrink_to_fit(&mut self) {
1176 self.vec.shrink_to_fit()
1179 /// Shrinks the capacity of this `String` with a lower bound.
1181 /// The capacity will remain at least as large as both the length
1182 /// and the supplied value.
1184 /// If the current capacity is less than the lower limit, this is a no-op.
1189 /// let mut s = String::from("foo");
1192 /// assert!(s.capacity() >= 100);
1194 /// s.shrink_to(10);
1195 /// assert!(s.capacity() >= 10);
1197 /// assert!(s.capacity() >= 3);
1199 #[cfg(not(no_global_oom_handling))]
1201 #[stable(feature = "shrink_to", since = "1.56.0")]
1202 pub fn shrink_to(&mut self, min_capacity: usize) {
1203 self.vec.shrink_to(min_capacity)
1206 /// Appends the given [`char`] to the end of this `String`.
1213 /// let mut s = String::from("abc");
1219 /// assert_eq!("abc123", s);
1221 #[cfg(not(no_global_oom_handling))]
1223 #[stable(feature = "rust1", since = "1.0.0")]
1224 pub fn push(&mut self, ch: char) {
1225 match ch.len_utf8() {
1226 1 => self.vec.push(ch as u8),
1227 _ => self.vec.extend_from_slice(ch.encode_utf8(&mut [0; 4]).as_bytes()),
1231 /// Returns a byte slice of this `String`'s contents.
1233 /// The inverse of this method is [`from_utf8`].
1235 /// [`from_utf8`]: String::from_utf8
1242 /// let s = String::from("hello");
1244 /// assert_eq!(&[104, 101, 108, 108, 111], s.as_bytes());
1248 #[stable(feature = "rust1", since = "1.0.0")]
1249 pub fn as_bytes(&self) -> &[u8] {
1253 /// Shortens this `String` to the specified length.
1255 /// If `new_len` is greater than the string's current length, this has no
1258 /// Note that this method has no effect on the allocated capacity
1263 /// Panics if `new_len` does not lie on a [`char`] boundary.
1270 /// let mut s = String::from("hello");
1274 /// assert_eq!("he", s);
1277 #[stable(feature = "rust1", since = "1.0.0")]
1278 pub fn truncate(&mut self, new_len: usize) {
1279 if new_len <= self.len() {
1280 assert!(self.is_char_boundary(new_len));
1281 self.vec.truncate(new_len)
1285 /// Removes the last character from the string buffer and returns it.
1287 /// Returns [`None`] if this `String` is empty.
1294 /// let mut s = String::from("foo");
1296 /// assert_eq!(s.pop(), Some('o'));
1297 /// assert_eq!(s.pop(), Some('o'));
1298 /// assert_eq!(s.pop(), Some('f'));
1300 /// assert_eq!(s.pop(), None);
1303 #[stable(feature = "rust1", since = "1.0.0")]
1304 pub fn pop(&mut self) -> Option<char> {
1305 let ch = self.chars().rev().next()?;
1306 let newlen = self.len() - ch.len_utf8();
1308 self.vec.set_len(newlen);
1313 /// Removes a [`char`] from this `String` at a byte position and returns it.
1315 /// This is an *O*(*n*) operation, as it requires copying every element in the
1320 /// Panics if `idx` is larger than or equal to the `String`'s length,
1321 /// or if it does not lie on a [`char`] boundary.
1328 /// let mut s = String::from("foo");
1330 /// assert_eq!(s.remove(0), 'f');
1331 /// assert_eq!(s.remove(1), 'o');
1332 /// assert_eq!(s.remove(0), 'o');
1335 #[stable(feature = "rust1", since = "1.0.0")]
1336 pub fn remove(&mut self, idx: usize) -> char {
1337 let ch = match self[idx..].chars().next() {
1339 None => panic!("cannot remove a char from the end of a string"),
1342 let next = idx + ch.len_utf8();
1343 let len = self.len();
1345 ptr::copy(self.vec.as_ptr().add(next), self.vec.as_mut_ptr().add(idx), len - next);
1346 self.vec.set_len(len - (next - idx));
1351 /// Remove all matches of pattern `pat` in the `String`.
1356 /// #![feature(string_remove_matches)]
1357 /// let mut s = String::from("Trees are not green, the sky is not blue.");
1358 /// s.remove_matches("not ");
1359 /// assert_eq!("Trees are green, the sky is blue.", s);
1362 /// Matches will be detected and removed iteratively, so in cases where
1363 /// patterns overlap, only the first pattern will be removed:
1366 /// #![feature(string_remove_matches)]
1367 /// let mut s = String::from("banana");
1368 /// s.remove_matches("ana");
1369 /// assert_eq!("bna", s);
1371 #[cfg(not(no_global_oom_handling))]
1372 #[unstable(feature = "string_remove_matches", reason = "new API", issue = "72826")]
1373 pub fn remove_matches<'a, P>(&'a mut self, pat: P)
1375 P: for<'x> Pattern<'x>,
1377 use core::str::pattern::Searcher;
1380 let mut searcher = pat.into_searcher(self);
1381 // Per Searcher::next:
1383 // A Match result needs to contain the whole matched pattern,
1384 // however Reject results may be split up into arbitrary many
1385 // adjacent fragments. Both ranges may have zero length.
1387 // In practice the implementation of Searcher::next_match tends to
1388 // be more efficient, so we use it here and do some work to invert
1389 // matches into rejections since that's what we want to copy below.
1391 let rejections: Vec<_> = from_fn(|| {
1392 let (start, end) = searcher.next_match()?;
1393 let prev_front = front;
1395 Some((prev_front, start))
1398 rejections.into_iter().chain(core::iter::once((front, self.len())))
1402 let ptr = self.vec.as_mut_ptr();
1404 for (start, end) in rejections {
1405 let count = end - start;
1407 // SAFETY: per Searcher::next:
1409 // The stream of Match and Reject values up to a Done will
1410 // contain index ranges that are adjacent, non-overlapping,
1411 // covering the whole haystack, and laying on utf8
1414 ptr::copy(ptr.add(start), ptr.add(len), count);
1421 self.vec.set_len(len);
1425 /// Retains only the characters specified by the predicate.
1427 /// In other words, remove all characters `c` such that `f(c)` returns `false`.
1428 /// This method operates in place, visiting each character exactly once in the
1429 /// original order, and preserves the order of the retained characters.
1434 /// let mut s = String::from("f_o_ob_ar");
1436 /// s.retain(|c| c != '_');
1438 /// assert_eq!(s, "foobar");
1441 /// Because the elements are visited exactly once in the original order,
1442 /// external state may be used to decide which elements to keep.
1445 /// let mut s = String::from("abcde");
1446 /// let keep = [false, true, true, false, true];
1447 /// let mut iter = keep.iter();
1448 /// s.retain(|_| *iter.next().unwrap());
1449 /// assert_eq!(s, "bce");
1452 #[stable(feature = "string_retain", since = "1.26.0")]
1453 pub fn retain<F>(&mut self, mut f: F)
1455 F: FnMut(char) -> bool,
1457 struct SetLenOnDrop<'a> {
1463 impl<'a> Drop for SetLenOnDrop<'a> {
1464 fn drop(&mut self) {
1465 let new_len = self.idx - self.del_bytes;
1466 debug_assert!(new_len <= self.s.len());
1467 unsafe { self.s.vec.set_len(new_len) };
1471 let len = self.len();
1472 let mut guard = SetLenOnDrop { s: self, idx: 0, del_bytes: 0 };
1474 while guard.idx < len {
1476 // SAFETY: `guard.idx` is positive-or-zero and less that len so the `get_unchecked`
1477 // is in bound. `self` is valid UTF-8 like string and the returned slice starts at
1478 // a unicode code point so the `Chars` always return one character.
1479 unsafe { guard.s.get_unchecked(guard.idx..len).chars().next().unwrap_unchecked() };
1480 let ch_len = ch.len_utf8();
1483 guard.del_bytes += ch_len;
1484 } else if guard.del_bytes > 0 {
1485 // SAFETY: `guard.idx` is in bound and `guard.del_bytes` represent the number of
1486 // bytes that are erased from the string so the resulting `guard.idx -
1487 // guard.del_bytes` always represent a valid unicode code point.
1489 // `guard.del_bytes` >= `ch.len_utf8()`, so taking a slice with `ch.len_utf8()` len
1491 ch.encode_utf8(unsafe {
1492 crate::slice::from_raw_parts_mut(
1493 guard.s.as_mut_ptr().add(guard.idx - guard.del_bytes),
1499 // Point idx to the next char
1500 guard.idx += ch_len;
1506 /// Inserts a character into this `String` at a byte position.
1508 /// This is an *O*(*n*) operation as it requires copying every element in the
1513 /// Panics if `idx` is larger than the `String`'s length, or if it does not
1514 /// lie on a [`char`] boundary.
1521 /// let mut s = String::with_capacity(3);
1523 /// s.insert(0, 'f');
1524 /// s.insert(1, 'o');
1525 /// s.insert(2, 'o');
1527 /// assert_eq!("foo", s);
1529 #[cfg(not(no_global_oom_handling))]
1531 #[stable(feature = "rust1", since = "1.0.0")]
1532 pub fn insert(&mut self, idx: usize, ch: char) {
1533 assert!(self.is_char_boundary(idx));
1534 let mut bits = [0; 4];
1535 let bits = ch.encode_utf8(&mut bits).as_bytes();
1538 self.insert_bytes(idx, bits);
1542 #[cfg(not(no_global_oom_handling))]
1543 unsafe fn insert_bytes(&mut self, idx: usize, bytes: &[u8]) {
1544 let len = self.len();
1545 let amt = bytes.len();
1546 self.vec.reserve(amt);
1549 ptr::copy(self.vec.as_ptr().add(idx), self.vec.as_mut_ptr().add(idx + amt), len - idx);
1550 ptr::copy_nonoverlapping(bytes.as_ptr(), self.vec.as_mut_ptr().add(idx), amt);
1551 self.vec.set_len(len + amt);
1555 /// Inserts a string slice into this `String` at a byte position.
1557 /// This is an *O*(*n*) operation as it requires copying every element in the
1562 /// Panics if `idx` is larger than the `String`'s length, or if it does not
1563 /// lie on a [`char`] boundary.
1570 /// let mut s = String::from("bar");
1572 /// s.insert_str(0, "foo");
1574 /// assert_eq!("foobar", s);
1576 #[cfg(not(no_global_oom_handling))]
1578 #[stable(feature = "insert_str", since = "1.16.0")]
1579 pub fn insert_str(&mut self, idx: usize, string: &str) {
1580 assert!(self.is_char_boundary(idx));
1583 self.insert_bytes(idx, string.as_bytes());
1587 /// Returns a mutable reference to the contents of this `String`.
1591 /// This function is unsafe because the returned `&mut Vec` allows writing
1592 /// bytes which are not valid UTF-8. If this constraint is violated, using
1593 /// the original `String` after dropping the `&mut Vec` may violate memory
1594 /// safety, as the rest of the standard library assumes that `String`s are
1602 /// let mut s = String::from("hello");
1605 /// let vec = s.as_mut_vec();
1606 /// assert_eq!(&[104, 101, 108, 108, 111][..], &vec[..]);
1610 /// assert_eq!(s, "olleh");
1613 #[stable(feature = "rust1", since = "1.0.0")]
1614 pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1618 /// Returns the length of this `String`, in bytes, not [`char`]s or
1619 /// graphemes. In other words, it might not be what a human considers the
1620 /// length of the string.
1627 /// let a = String::from("foo");
1628 /// assert_eq!(a.len(), 3);
1630 /// let fancy_f = String::from("Ζoo");
1631 /// assert_eq!(fancy_f.len(), 4);
1632 /// assert_eq!(fancy_f.chars().count(), 3);
1636 #[stable(feature = "rust1", since = "1.0.0")]
1637 pub fn len(&self) -> usize {
1641 /// Returns `true` if this `String` has a length of zero, and `false` otherwise.
1648 /// let mut v = String::new();
1649 /// assert!(v.is_empty());
1652 /// assert!(!v.is_empty());
1656 #[stable(feature = "rust1", since = "1.0.0")]
1657 pub fn is_empty(&self) -> bool {
1661 /// Splits the string into two at the given byte index.
1663 /// Returns a newly allocated `String`. `self` contains bytes `[0, at)`, and
1664 /// the returned `String` contains bytes `[at, len)`. `at` must be on the
1665 /// boundary of a UTF-8 code point.
1667 /// Note that the capacity of `self` does not change.
1671 /// Panics if `at` is not on a `UTF-8` code point boundary, or if it is beyond the last
1672 /// code point of the string.
1678 /// let mut hello = String::from("Hello, World!");
1679 /// let world = hello.split_off(7);
1680 /// assert_eq!(hello, "Hello, ");
1681 /// assert_eq!(world, "World!");
1684 #[cfg(not(no_global_oom_handling))]
1686 #[stable(feature = "string_split_off", since = "1.16.0")]
1687 #[must_use = "use `.truncate()` if you don't need the other half"]
1688 pub fn split_off(&mut self, at: usize) -> String {
1689 assert!(self.is_char_boundary(at));
1690 let other = self.vec.split_off(at);
1691 unsafe { String::from_utf8_unchecked(other) }
1694 /// Truncates this `String`, removing all contents.
1696 /// While this means the `String` will have a length of zero, it does not
1697 /// touch its capacity.
1704 /// let mut s = String::from("foo");
1708 /// assert!(s.is_empty());
1709 /// assert_eq!(0, s.len());
1710 /// assert_eq!(3, s.capacity());
1713 #[stable(feature = "rust1", since = "1.0.0")]
1714 pub fn clear(&mut self) {
1718 /// Removes the specified range from the string in bulk, returning all
1719 /// removed characters as an iterator.
1721 /// The returned iterator keeps a mutable borrow on the string to optimize
1722 /// its implementation.
1726 /// Panics if the starting point or end point do not lie on a [`char`]
1727 /// boundary, or if they're out of bounds.
1731 /// If the returned iterator goes out of scope without being dropped (due to
1732 /// [`core::mem::forget`], for example), the string may still contain a copy
1733 /// of any drained characters, or may have lost characters arbitrarily,
1734 /// including characters outside the range.
1741 /// let mut s = String::from("Ξ± is alpha, Ξ² is beta");
1742 /// let beta_offset = s.find('Ξ²').unwrap_or(s.len());
1744 /// // Remove the range up until the Ξ² from the string
1745 /// let t: String = s.drain(..beta_offset).collect();
1746 /// assert_eq!(t, "Ξ± is alpha, ");
1747 /// assert_eq!(s, "Ξ² is beta");
1749 /// // A full range clears the string, like `clear()` does
1751 /// assert_eq!(s, "");
1753 #[stable(feature = "drain", since = "1.6.0")]
1754 pub fn drain<R>(&mut self, range: R) -> Drain<'_>
1756 R: RangeBounds<usize>,
1760 // The String version of Drain does not have the memory safety issues
1761 // of the vector version. The data is just plain bytes.
1762 // Because the range removal happens in Drop, if the Drain iterator is leaked,
1763 // the removal will not happen.
1764 let Range { start, end } = slice::range(range, ..self.len());
1765 assert!(self.is_char_boundary(start));
1766 assert!(self.is_char_boundary(end));
1768 // Take out two simultaneous borrows. The &mut String won't be accessed
1769 // until iteration is over, in Drop.
1770 let self_ptr = self as *mut _;
1771 // SAFETY: `slice::range` and `is_char_boundary` do the appropriate bounds checks.
1772 let chars_iter = unsafe { self.get_unchecked(start..end) }.chars();
1774 Drain { start, end, iter: chars_iter, string: self_ptr }
1777 /// Removes the specified range in the string,
1778 /// and replaces it with the given string.
1779 /// The given string doesn't need to be the same length as the range.
1783 /// Panics if the starting point or end point do not lie on a [`char`]
1784 /// boundary, or if they're out of bounds.
1791 /// let mut s = String::from("Ξ± is alpha, Ξ² is beta");
1792 /// let beta_offset = s.find('Ξ²').unwrap_or(s.len());
1794 /// // Replace the range up until the Ξ² from the string
1795 /// s.replace_range(..beta_offset, "Ξ is capital alpha; ");
1796 /// assert_eq!(s, "Ξ is capital alpha; Ξ² is beta");
1798 #[cfg(not(no_global_oom_handling))]
1799 #[stable(feature = "splice", since = "1.27.0")]
1800 pub fn replace_range<R>(&mut self, range: R, replace_with: &str)
1802 R: RangeBounds<usize>,
1806 // Replace_range does not have the memory safety issues of a vector Splice.
1807 // of the vector version. The data is just plain bytes.
1809 // WARNING: Inlining this variable would be unsound (#81138)
1810 let start = range.start_bound();
1812 Included(&n) => assert!(self.is_char_boundary(n)),
1813 Excluded(&n) => assert!(self.is_char_boundary(n + 1)),
1816 // WARNING: Inlining this variable would be unsound (#81138)
1817 let end = range.end_bound();
1819 Included(&n) => assert!(self.is_char_boundary(n + 1)),
1820 Excluded(&n) => assert!(self.is_char_boundary(n)),
1824 // Using `range` again would be unsound (#81138)
1825 // We assume the bounds reported by `range` remain the same, but
1826 // an adversarial implementation could change between calls
1827 unsafe { self.as_mut_vec() }.splice((start, end), replace_with.bytes());
1830 /// Converts this `String` into a <code>[Box]<[str]></code>.
1832 /// This will drop any excess capacity.
1834 /// [str]: prim@str "str"
1841 /// let s = String::from("hello");
1843 /// let b = s.into_boxed_str();
1845 #[cfg(not(no_global_oom_handling))]
1846 #[stable(feature = "box_str", since = "1.4.0")]
1847 #[must_use = "`self` will be dropped if the result is not used"]
1849 pub fn into_boxed_str(self) -> Box<str> {
1850 let slice = self.vec.into_boxed_slice();
1851 unsafe { from_boxed_utf8_unchecked(slice) }
1855 impl FromUtf8Error {
1856 /// Returns a slice of [`u8`]s bytes that were attempted to convert to a `String`.
1863 /// // some invalid bytes, in a vector
1864 /// let bytes = vec![0, 159];
1866 /// let value = String::from_utf8(bytes);
1868 /// assert_eq!(&[0, 159], value.unwrap_err().as_bytes());
1871 #[stable(feature = "from_utf8_error_as_bytes", since = "1.26.0")]
1872 pub fn as_bytes(&self) -> &[u8] {
1876 /// Returns the bytes that were attempted to convert to a `String`.
1878 /// This method is carefully constructed to avoid allocation. It will
1879 /// consume the error, moving out the bytes, so that a copy of the bytes
1880 /// does not need to be made.
1887 /// // some invalid bytes, in a vector
1888 /// let bytes = vec![0, 159];
1890 /// let value = String::from_utf8(bytes);
1892 /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
1894 #[must_use = "`self` will be dropped if the result is not used"]
1895 #[stable(feature = "rust1", since = "1.0.0")]
1896 pub fn into_bytes(self) -> Vec<u8> {
1900 /// Fetch a `Utf8Error` to get more details about the conversion failure.
1902 /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
1903 /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
1904 /// an analogue to `FromUtf8Error`. See its documentation for more details
1907 /// [`std::str`]: core::str "std::str"
1908 /// [`&str`]: prim@str "&str"
1915 /// // some invalid bytes, in a vector
1916 /// let bytes = vec![0, 159];
1918 /// let error = String::from_utf8(bytes).unwrap_err().utf8_error();
1920 /// // the first byte is invalid here
1921 /// assert_eq!(1, error.valid_up_to());
1924 #[stable(feature = "rust1", since = "1.0.0")]
1925 pub fn utf8_error(&self) -> Utf8Error {
1930 #[stable(feature = "rust1", since = "1.0.0")]
1931 impl fmt::Display for FromUtf8Error {
1932 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1933 fmt::Display::fmt(&self.error, f)
1937 #[stable(feature = "rust1", since = "1.0.0")]
1938 impl fmt::Display for FromUtf16Error {
1939 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1940 fmt::Display::fmt("invalid utf-16: lone surrogate found", f)
1944 #[cfg(not(bootstrap))]
1945 #[stable(feature = "rust1", since = "1.0.0")]
1946 impl Error for FromUtf8Error {
1947 #[allow(deprecated)]
1948 fn description(&self) -> &str {
1953 #[cfg(not(bootstrap))]
1954 #[stable(feature = "rust1", since = "1.0.0")]
1955 impl Error for FromUtf16Error {
1956 #[allow(deprecated)]
1957 fn description(&self) -> &str {
1962 #[cfg(not(no_global_oom_handling))]
1963 #[stable(feature = "rust1", since = "1.0.0")]
1964 impl Clone for String {
1965 fn clone(&self) -> Self {
1966 String { vec: self.vec.clone() }
1969 fn clone_from(&mut self, source: &Self) {
1970 self.vec.clone_from(&source.vec);
1974 #[cfg(not(no_global_oom_handling))]
1975 #[stable(feature = "rust1", since = "1.0.0")]
1976 impl FromIterator<char> for String {
1977 fn from_iter<I: IntoIterator<Item = char>>(iter: I) -> String {
1978 let mut buf = String::new();
1984 #[cfg(not(no_global_oom_handling))]
1985 #[stable(feature = "string_from_iter_by_ref", since = "1.17.0")]
1986 impl<'a> FromIterator<&'a char> for String {
1987 fn from_iter<I: IntoIterator<Item = &'a char>>(iter: I) -> String {
1988 let mut buf = String::new();
1994 #[cfg(not(no_global_oom_handling))]
1995 #[stable(feature = "rust1", since = "1.0.0")]
1996 impl<'a> FromIterator<&'a str> for String {
1997 fn from_iter<I: IntoIterator<Item = &'a str>>(iter: I) -> String {
1998 let mut buf = String::new();
2004 #[cfg(not(no_global_oom_handling))]
2005 #[stable(feature = "extend_string", since = "1.4.0")]
2006 impl FromIterator<String> for String {
2007 fn from_iter<I: IntoIterator<Item = String>>(iter: I) -> String {
2008 let mut iterator = iter.into_iter();
2010 // Because we're iterating over `String`s, we can avoid at least
2011 // one allocation by getting the first string from the iterator
2012 // and appending to it all the subsequent strings.
2013 match iterator.next() {
2014 None => String::new(),
2016 buf.extend(iterator);
2023 #[cfg(not(no_global_oom_handling))]
2024 #[stable(feature = "box_str2", since = "1.45.0")]
2025 impl FromIterator<Box<str>> for String {
2026 fn from_iter<I: IntoIterator<Item = Box<str>>>(iter: I) -> String {
2027 let mut buf = String::new();
2033 #[cfg(not(no_global_oom_handling))]
2034 #[stable(feature = "herd_cows", since = "1.19.0")]
2035 impl<'a> FromIterator<Cow<'a, str>> for String {
2036 fn from_iter<I: IntoIterator<Item = Cow<'a, str>>>(iter: I) -> String {
2037 let mut iterator = iter.into_iter();
2039 // Because we're iterating over CoWs, we can (potentially) avoid at least
2040 // one allocation by getting the first item and appending to it all the
2041 // subsequent items.
2042 match iterator.next() {
2043 None => String::new(),
2045 let mut buf = cow.into_owned();
2046 buf.extend(iterator);
2053 #[cfg(not(no_global_oom_handling))]
2054 #[stable(feature = "rust1", since = "1.0.0")]
2055 impl Extend<char> for String {
2056 fn extend<I: IntoIterator<Item = char>>(&mut self, iter: I) {
2057 let iterator = iter.into_iter();
2058 let (lower_bound, _) = iterator.size_hint();
2059 self.reserve(lower_bound);
2060 iterator.for_each(move |c| self.push(c));
2064 fn extend_one(&mut self, c: char) {
2069 fn extend_reserve(&mut self, additional: usize) {
2070 self.reserve(additional);
2074 #[cfg(not(no_global_oom_handling))]
2075 #[stable(feature = "extend_ref", since = "1.2.0")]
2076 impl<'a> Extend<&'a char> for String {
2077 fn extend<I: IntoIterator<Item = &'a char>>(&mut self, iter: I) {
2078 self.extend(iter.into_iter().cloned());
2082 fn extend_one(&mut self, &c: &'a char) {
2087 fn extend_reserve(&mut self, additional: usize) {
2088 self.reserve(additional);
2092 #[cfg(not(no_global_oom_handling))]
2093 #[stable(feature = "rust1", since = "1.0.0")]
2094 impl<'a> Extend<&'a str> for String {
2095 fn extend<I: IntoIterator<Item = &'a str>>(&mut self, iter: I) {
2096 iter.into_iter().for_each(move |s| self.push_str(s));
2100 fn extend_one(&mut self, s: &'a str) {
2105 #[cfg(not(no_global_oom_handling))]
2106 #[stable(feature = "box_str2", since = "1.45.0")]
2107 impl Extend<Box<str>> for String {
2108 fn extend<I: IntoIterator<Item = Box<str>>>(&mut self, iter: I) {
2109 iter.into_iter().for_each(move |s| self.push_str(&s));
2113 #[cfg(not(no_global_oom_handling))]
2114 #[stable(feature = "extend_string", since = "1.4.0")]
2115 impl Extend<String> for String {
2116 fn extend<I: IntoIterator<Item = String>>(&mut self, iter: I) {
2117 iter.into_iter().for_each(move |s| self.push_str(&s));
2121 fn extend_one(&mut self, s: String) {
2126 #[cfg(not(no_global_oom_handling))]
2127 #[stable(feature = "herd_cows", since = "1.19.0")]
2128 impl<'a> Extend<Cow<'a, str>> for String {
2129 fn extend<I: IntoIterator<Item = Cow<'a, str>>>(&mut self, iter: I) {
2130 iter.into_iter().for_each(move |s| self.push_str(&s));
2134 fn extend_one(&mut self, s: Cow<'a, str>) {
2139 /// A convenience impl that delegates to the impl for `&str`.
2144 /// assert_eq!(String::from("Hello world").find("world"), Some(6));
2147 feature = "pattern",
2148 reason = "API not fully fleshed out and ready to be stabilized",
2151 impl<'a, 'b> Pattern<'a> for &'b String {
2152 type Searcher = <&'b str as Pattern<'a>>::Searcher;
2154 fn into_searcher(self, haystack: &'a str) -> <&'b str as Pattern<'a>>::Searcher {
2155 self[..].into_searcher(haystack)
2159 fn is_contained_in(self, haystack: &'a str) -> bool {
2160 self[..].is_contained_in(haystack)
2164 fn is_prefix_of(self, haystack: &'a str) -> bool {
2165 self[..].is_prefix_of(haystack)
2169 fn strip_prefix_of(self, haystack: &'a str) -> Option<&'a str> {
2170 self[..].strip_prefix_of(haystack)
2174 fn is_suffix_of(self, haystack: &'a str) -> bool {
2175 self[..].is_suffix_of(haystack)
2179 fn strip_suffix_of(self, haystack: &'a str) -> Option<&'a str> {
2180 self[..].strip_suffix_of(haystack)
2184 #[stable(feature = "rust1", since = "1.0.0")]
2185 impl PartialEq for String {
2187 fn eq(&self, other: &String) -> bool {
2188 PartialEq::eq(&self[..], &other[..])
2191 fn ne(&self, other: &String) -> bool {
2192 PartialEq::ne(&self[..], &other[..])
2196 macro_rules! impl_eq {
2197 ($lhs:ty, $rhs: ty) => {
2198 #[stable(feature = "rust1", since = "1.0.0")]
2199 #[allow(unused_lifetimes)]
2200 impl<'a, 'b> PartialEq<$rhs> for $lhs {
2202 fn eq(&self, other: &$rhs) -> bool {
2203 PartialEq::eq(&self[..], &other[..])
2206 fn ne(&self, other: &$rhs) -> bool {
2207 PartialEq::ne(&self[..], &other[..])
2211 #[stable(feature = "rust1", since = "1.0.0")]
2212 #[allow(unused_lifetimes)]
2213 impl<'a, 'b> PartialEq<$lhs> for $rhs {
2215 fn eq(&self, other: &$lhs) -> bool {
2216 PartialEq::eq(&self[..], &other[..])
2219 fn ne(&self, other: &$lhs) -> bool {
2220 PartialEq::ne(&self[..], &other[..])
2226 impl_eq! { String, str }
2227 impl_eq! { String, &'a str }
2228 #[cfg(not(no_global_oom_handling))]
2229 impl_eq! { Cow<'a, str>, str }
2230 #[cfg(not(no_global_oom_handling))]
2231 impl_eq! { Cow<'a, str>, &'b str }
2232 #[cfg(not(no_global_oom_handling))]
2233 impl_eq! { Cow<'a, str>, String }
2235 #[stable(feature = "rust1", since = "1.0.0")]
2236 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
2237 impl const Default for String {
2238 /// Creates an empty `String`.
2240 fn default() -> String {
2245 #[stable(feature = "rust1", since = "1.0.0")]
2246 impl fmt::Display for String {
2248 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2249 fmt::Display::fmt(&**self, f)
2253 #[stable(feature = "rust1", since = "1.0.0")]
2254 impl fmt::Debug for String {
2256 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2257 fmt::Debug::fmt(&**self, f)
2261 #[stable(feature = "rust1", since = "1.0.0")]
2262 impl hash::Hash for String {
2264 fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
2265 (**self).hash(hasher)
2269 /// Implements the `+` operator for concatenating two strings.
2271 /// This consumes the `String` on the left-hand side and re-uses its buffer (growing it if
2272 /// necessary). This is done to avoid allocating a new `String` and copying the entire contents on
2273 /// every operation, which would lead to *O*(*n*^2) running time when building an *n*-byte string by
2274 /// repeated concatenation.
2276 /// The string on the right-hand side is only borrowed; its contents are copied into the returned
2281 /// Concatenating two `String`s takes the first by value and borrows the second:
2284 /// let a = String::from("hello");
2285 /// let b = String::from(" world");
2287 /// // `a` is moved and can no longer be used here.
2290 /// If you want to keep using the first `String`, you can clone it and append to the clone instead:
2293 /// let a = String::from("hello");
2294 /// let b = String::from(" world");
2295 /// let c = a.clone() + &b;
2296 /// // `a` is still valid here.
2299 /// Concatenating `&str` slices can be done by converting the first to a `String`:
2302 /// let a = "hello";
2303 /// let b = " world";
2304 /// let c = a.to_string() + b;
2306 #[cfg(not(no_global_oom_handling))]
2307 #[stable(feature = "rust1", since = "1.0.0")]
2308 impl Add<&str> for String {
2309 type Output = String;
2312 fn add(mut self, other: &str) -> String {
2313 self.push_str(other);
2318 /// Implements the `+=` operator for appending to a `String`.
2320 /// This has the same behavior as the [`push_str`][String::push_str] method.
2321 #[cfg(not(no_global_oom_handling))]
2322 #[stable(feature = "stringaddassign", since = "1.12.0")]
2323 impl AddAssign<&str> for String {
2325 fn add_assign(&mut self, other: &str) {
2326 self.push_str(other);
2330 #[stable(feature = "rust1", since = "1.0.0")]
2331 impl ops::Index<ops::Range<usize>> for String {
2335 fn index(&self, index: ops::Range<usize>) -> &str {
2339 #[stable(feature = "rust1", since = "1.0.0")]
2340 impl ops::Index<ops::RangeTo<usize>> for String {
2344 fn index(&self, index: ops::RangeTo<usize>) -> &str {
2348 #[stable(feature = "rust1", since = "1.0.0")]
2349 impl ops::Index<ops::RangeFrom<usize>> for String {
2353 fn index(&self, index: ops::RangeFrom<usize>) -> &str {
2357 #[stable(feature = "rust1", since = "1.0.0")]
2358 impl ops::Index<ops::RangeFull> for String {
2362 fn index(&self, _index: ops::RangeFull) -> &str {
2363 unsafe { str::from_utf8_unchecked(&self.vec) }
2366 #[stable(feature = "inclusive_range", since = "1.26.0")]
2367 impl ops::Index<ops::RangeInclusive<usize>> for String {
2371 fn index(&self, index: ops::RangeInclusive<usize>) -> &str {
2372 Index::index(&**self, index)
2375 #[stable(feature = "inclusive_range", since = "1.26.0")]
2376 impl ops::Index<ops::RangeToInclusive<usize>> for String {
2380 fn index(&self, index: ops::RangeToInclusive<usize>) -> &str {
2381 Index::index(&**self, index)
2385 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2386 impl ops::IndexMut<ops::Range<usize>> for String {
2388 fn index_mut(&mut self, index: ops::Range<usize>) -> &mut str {
2389 &mut self[..][index]
2392 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2393 impl ops::IndexMut<ops::RangeTo<usize>> for String {
2395 fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut str {
2396 &mut self[..][index]
2399 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2400 impl ops::IndexMut<ops::RangeFrom<usize>> for String {
2402 fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut str {
2403 &mut self[..][index]
2406 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2407 impl ops::IndexMut<ops::RangeFull> for String {
2409 fn index_mut(&mut self, _index: ops::RangeFull) -> &mut str {
2410 unsafe { str::from_utf8_unchecked_mut(&mut *self.vec) }
2413 #[stable(feature = "inclusive_range", since = "1.26.0")]
2414 impl ops::IndexMut<ops::RangeInclusive<usize>> for String {
2416 fn index_mut(&mut self, index: ops::RangeInclusive<usize>) -> &mut str {
2417 IndexMut::index_mut(&mut **self, index)
2420 #[stable(feature = "inclusive_range", since = "1.26.0")]
2421 impl ops::IndexMut<ops::RangeToInclusive<usize>> for String {
2423 fn index_mut(&mut self, index: ops::RangeToInclusive<usize>) -> &mut str {
2424 IndexMut::index_mut(&mut **self, index)
2428 #[stable(feature = "rust1", since = "1.0.0")]
2429 impl ops::Deref for String {
2433 fn deref(&self) -> &str {
2434 unsafe { str::from_utf8_unchecked(&self.vec) }
2438 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2439 impl ops::DerefMut for String {
2441 fn deref_mut(&mut self) -> &mut str {
2442 unsafe { str::from_utf8_unchecked_mut(&mut *self.vec) }
2446 /// A type alias for [`Infallible`].
2448 /// This alias exists for backwards compatibility, and may be eventually deprecated.
2450 /// [`Infallible`]: core::convert::Infallible "convert::Infallible"
2451 #[stable(feature = "str_parse_error", since = "1.5.0")]
2452 pub type ParseError = core::convert::Infallible;
2454 #[cfg(not(no_global_oom_handling))]
2455 #[stable(feature = "rust1", since = "1.0.0")]
2456 impl FromStr for String {
2457 type Err = core::convert::Infallible;
2459 fn from_str(s: &str) -> Result<String, Self::Err> {
2464 /// A trait for converting a value to a `String`.
2466 /// This trait is automatically implemented for any type which implements the
2467 /// [`Display`] trait. As such, `ToString` shouldn't be implemented directly:
2468 /// [`Display`] should be implemented instead, and you get the `ToString`
2469 /// implementation for free.
2471 /// [`Display`]: fmt::Display
2472 #[cfg_attr(not(test), rustc_diagnostic_item = "ToString")]
2473 #[stable(feature = "rust1", since = "1.0.0")]
2474 pub trait ToString {
2475 /// Converts the given value to a `String`.
2483 /// let five = String::from("5");
2485 /// assert_eq!(five, i.to_string());
2487 #[rustc_conversion_suggestion]
2488 #[stable(feature = "rust1", since = "1.0.0")]
2489 fn to_string(&self) -> String;
2494 /// In this implementation, the `to_string` method panics
2495 /// if the `Display` implementation returns an error.
2496 /// This indicates an incorrect `Display` implementation
2497 /// since `fmt::Write for String` never returns an error itself.
2498 #[cfg(not(no_global_oom_handling))]
2499 #[stable(feature = "rust1", since = "1.0.0")]
2500 impl<T: fmt::Display + ?Sized> ToString for T {
2501 // A common guideline is to not inline generic functions. However,
2502 // removing `#[inline]` from this method causes non-negligible regressions.
2503 // See <https://github.com/rust-lang/rust/pull/74852>, the last attempt
2504 // to try to remove it.
2506 default fn to_string(&self) -> String {
2507 let mut buf = String::new();
2508 let mut formatter = core::fmt::Formatter::new(&mut buf);
2509 // Bypass format_args!() to avoid write_str with zero-length strs
2510 fmt::Display::fmt(self, &mut formatter)
2511 .expect("a Display implementation returned an error unexpectedly");
2516 #[cfg(not(no_global_oom_handling))]
2517 #[stable(feature = "char_to_string_specialization", since = "1.46.0")]
2518 impl ToString for char {
2520 fn to_string(&self) -> String {
2521 String::from(self.encode_utf8(&mut [0; 4]))
2525 #[cfg(not(no_global_oom_handling))]
2526 #[stable(feature = "u8_to_string_specialization", since = "1.54.0")]
2527 impl ToString for u8 {
2529 fn to_string(&self) -> String {
2530 let mut buf = String::with_capacity(3);
2534 buf.push((b'0' + n / 100) as char);
2537 buf.push((b'0' + n / 10) as char);
2540 buf.push((b'0' + n) as char);
2545 #[cfg(not(no_global_oom_handling))]
2546 #[stable(feature = "i8_to_string_specialization", since = "1.54.0")]
2547 impl ToString for i8 {
2549 fn to_string(&self) -> String {
2550 let mut buf = String::with_capacity(4);
2551 if self.is_negative() {
2554 let mut n = self.unsigned_abs();
2560 buf.push((b'0' + n / 10) as char);
2563 buf.push((b'0' + n) as char);
2568 #[cfg(not(no_global_oom_handling))]
2569 #[stable(feature = "str_to_string_specialization", since = "1.9.0")]
2570 impl ToString for str {
2572 fn to_string(&self) -> String {
2577 #[cfg(not(no_global_oom_handling))]
2578 #[stable(feature = "cow_str_to_string_specialization", since = "1.17.0")]
2579 impl ToString for Cow<'_, str> {
2581 fn to_string(&self) -> String {
2586 #[cfg(not(no_global_oom_handling))]
2587 #[stable(feature = "string_to_string_specialization", since = "1.17.0")]
2588 impl ToString for String {
2590 fn to_string(&self) -> String {
2595 #[stable(feature = "rust1", since = "1.0.0")]
2596 impl AsRef<str> for String {
2598 fn as_ref(&self) -> &str {
2603 #[stable(feature = "string_as_mut", since = "1.43.0")]
2604 impl AsMut<str> for String {
2606 fn as_mut(&mut self) -> &mut str {
2611 #[stable(feature = "rust1", since = "1.0.0")]
2612 impl AsRef<[u8]> for String {
2614 fn as_ref(&self) -> &[u8] {
2619 #[cfg(not(no_global_oom_handling))]
2620 #[stable(feature = "rust1", since = "1.0.0")]
2621 impl From<&str> for String {
2622 /// Converts a `&str` into a [`String`].
2624 /// The result is allocated on the heap.
2626 fn from(s: &str) -> String {
2631 #[cfg(not(no_global_oom_handling))]
2632 #[stable(feature = "from_mut_str_for_string", since = "1.44.0")]
2633 impl From<&mut str> for String {
2634 /// Converts a `&mut str` into a [`String`].
2636 /// The result is allocated on the heap.
2638 fn from(s: &mut str) -> String {
2643 #[cfg(not(no_global_oom_handling))]
2644 #[stable(feature = "from_ref_string", since = "1.35.0")]
2645 impl From<&String> for String {
2646 /// Converts a `&String` into a [`String`].
2648 /// This clones `s` and returns the clone.
2650 fn from(s: &String) -> String {
2655 // note: test pulls in libstd, which causes errors here
2657 #[stable(feature = "string_from_box", since = "1.18.0")]
2658 impl From<Box<str>> for String {
2659 /// Converts the given boxed `str` slice to a [`String`].
2660 /// It is notable that the `str` slice is owned.
2667 /// let s1: String = String::from("hello world");
2668 /// let s2: Box<str> = s1.into_boxed_str();
2669 /// let s3: String = String::from(s2);
2671 /// assert_eq!("hello world", s3)
2673 fn from(s: Box<str>) -> String {
2678 #[cfg(not(no_global_oom_handling))]
2679 #[stable(feature = "box_from_str", since = "1.20.0")]
2680 impl From<String> for Box<str> {
2681 /// Converts the given [`String`] to a boxed `str` slice that is owned.
2688 /// let s1: String = String::from("hello world");
2689 /// let s2: Box<str> = Box::from(s1);
2690 /// let s3: String = String::from(s2);
2692 /// assert_eq!("hello world", s3)
2694 fn from(s: String) -> Box<str> {
2699 #[cfg(not(no_global_oom_handling))]
2700 #[stable(feature = "string_from_cow_str", since = "1.14.0")]
2701 impl<'a> From<Cow<'a, str>> for String {
2702 /// Converts a clone-on-write string to an owned
2703 /// instance of [`String`].
2705 /// This extracts the owned string,
2706 /// clones the string if it is not already owned.
2711 /// # use std::borrow::Cow;
2712 /// // If the string is not owned...
2713 /// let cow: Cow<str> = Cow::Borrowed("eggplant");
2714 /// // It will allocate on the heap and copy the string.
2715 /// let owned: String = String::from(cow);
2716 /// assert_eq!(&owned[..], "eggplant");
2718 fn from(s: Cow<'a, str>) -> String {
2723 #[cfg(not(no_global_oom_handling))]
2724 #[stable(feature = "rust1", since = "1.0.0")]
2725 impl<'a> From<&'a str> for Cow<'a, str> {
2726 /// Converts a string slice into a [`Borrowed`] variant.
2727 /// No heap allocation is performed, and the string
2733 /// # use std::borrow::Cow;
2734 /// assert_eq!(Cow::from("eggplant"), Cow::Borrowed("eggplant"));
2737 /// [`Borrowed`]: crate::borrow::Cow::Borrowed "borrow::Cow::Borrowed"
2739 fn from(s: &'a str) -> Cow<'a, str> {
2744 #[cfg(not(no_global_oom_handling))]
2745 #[stable(feature = "rust1", since = "1.0.0")]
2746 impl<'a> From<String> for Cow<'a, str> {
2747 /// Converts a [`String`] into an [`Owned`] variant.
2748 /// No heap allocation is performed, and the string
2754 /// # use std::borrow::Cow;
2755 /// let s = "eggplant".to_string();
2756 /// let s2 = "eggplant".to_string();
2757 /// assert_eq!(Cow::from(s), Cow::<'static, str>::Owned(s2));
2760 /// [`Owned`]: crate::borrow::Cow::Owned "borrow::Cow::Owned"
2762 fn from(s: String) -> Cow<'a, str> {
2767 #[cfg(not(no_global_oom_handling))]
2768 #[stable(feature = "cow_from_string_ref", since = "1.28.0")]
2769 impl<'a> From<&'a String> for Cow<'a, str> {
2770 /// Converts a [`String`] reference into a [`Borrowed`] variant.
2771 /// No heap allocation is performed, and the string
2777 /// # use std::borrow::Cow;
2778 /// let s = "eggplant".to_string();
2779 /// assert_eq!(Cow::from(&s), Cow::Borrowed("eggplant"));
2782 /// [`Borrowed`]: crate::borrow::Cow::Borrowed "borrow::Cow::Borrowed"
2784 fn from(s: &'a String) -> Cow<'a, str> {
2785 Cow::Borrowed(s.as_str())
2789 #[cfg(not(no_global_oom_handling))]
2790 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2791 impl<'a> FromIterator<char> for Cow<'a, str> {
2792 fn from_iter<I: IntoIterator<Item = char>>(it: I) -> Cow<'a, str> {
2793 Cow::Owned(FromIterator::from_iter(it))
2797 #[cfg(not(no_global_oom_handling))]
2798 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2799 impl<'a, 'b> FromIterator<&'b str> for Cow<'a, str> {
2800 fn from_iter<I: IntoIterator<Item = &'b str>>(it: I) -> Cow<'a, str> {
2801 Cow::Owned(FromIterator::from_iter(it))
2805 #[cfg(not(no_global_oom_handling))]
2806 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2807 impl<'a> FromIterator<String> for Cow<'a, str> {
2808 fn from_iter<I: IntoIterator<Item = String>>(it: I) -> Cow<'a, str> {
2809 Cow::Owned(FromIterator::from_iter(it))
2813 #[stable(feature = "from_string_for_vec_u8", since = "1.14.0")]
2814 impl From<String> for Vec<u8> {
2815 /// Converts the given [`String`] to a vector [`Vec`] that holds values of type [`u8`].
2822 /// let s1 = String::from("hello world");
2823 /// let v1 = Vec::from(s1);
2826 /// println!("{b}");
2829 fn from(string: String) -> Vec<u8> {
2834 #[cfg(not(no_global_oom_handling))]
2835 #[stable(feature = "rust1", since = "1.0.0")]
2836 impl fmt::Write for String {
2838 fn write_str(&mut self, s: &str) -> fmt::Result {
2844 fn write_char(&mut self, c: char) -> fmt::Result {
2850 /// A draining iterator for `String`.
2852 /// This struct is created by the [`drain`] method on [`String`]. See its
2853 /// documentation for more.
2855 /// [`drain`]: String::drain
2856 #[stable(feature = "drain", since = "1.6.0")]
2857 pub struct Drain<'a> {
2858 /// Will be used as &'a mut String in the destructor
2859 string: *mut String,
2860 /// Start of part to remove
2862 /// End of part to remove
2864 /// Current remaining range to remove
2868 #[stable(feature = "collection_debug", since = "1.17.0")]
2869 impl fmt::Debug for Drain<'_> {
2870 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2871 f.debug_tuple("Drain").field(&self.as_str()).finish()
2875 #[stable(feature = "drain", since = "1.6.0")]
2876 unsafe impl Sync for Drain<'_> {}
2877 #[stable(feature = "drain", since = "1.6.0")]
2878 unsafe impl Send for Drain<'_> {}
2880 #[stable(feature = "drain", since = "1.6.0")]
2881 impl Drop for Drain<'_> {
2882 fn drop(&mut self) {
2884 // Use Vec::drain. "Reaffirm" the bounds checks to avoid
2885 // panic code being inserted again.
2886 let self_vec = (*self.string).as_mut_vec();
2887 if self.start <= self.end && self.end <= self_vec.len() {
2888 self_vec.drain(self.start..self.end);
2894 impl<'a> Drain<'a> {
2895 /// Returns the remaining (sub)string of this iterator as a slice.
2900 /// let mut s = String::from("abc");
2901 /// let mut drain = s.drain(..);
2902 /// assert_eq!(drain.as_str(), "abc");
2903 /// let _ = drain.next().unwrap();
2904 /// assert_eq!(drain.as_str(), "bc");
2907 #[stable(feature = "string_drain_as_str", since = "1.55.0")]
2908 pub fn as_str(&self) -> &str {
2913 #[stable(feature = "string_drain_as_str", since = "1.55.0")]
2914 impl<'a> AsRef<str> for Drain<'a> {
2915 fn as_ref(&self) -> &str {
2920 #[stable(feature = "string_drain_as_str", since = "1.55.0")]
2921 impl<'a> AsRef<[u8]> for Drain<'a> {
2922 fn as_ref(&self) -> &[u8] {
2923 self.as_str().as_bytes()
2927 #[stable(feature = "drain", since = "1.6.0")]
2928 impl Iterator for Drain<'_> {
2932 fn next(&mut self) -> Option<char> {
2936 fn size_hint(&self) -> (usize, Option<usize>) {
2937 self.iter.size_hint()
2941 fn last(mut self) -> Option<char> {
2946 #[stable(feature = "drain", since = "1.6.0")]
2947 impl DoubleEndedIterator for Drain<'_> {
2949 fn next_back(&mut self) -> Option<char> {
2950 self.iter.next_back()
2954 #[stable(feature = "fused", since = "1.26.0")]
2955 impl FusedIterator for Drain<'_> {}
2957 #[cfg(not(no_global_oom_handling))]
2958 #[stable(feature = "from_char_for_string", since = "1.46.0")]
2959 impl From<char> for String {
2960 /// Allocates an owned [`String`] from a single character.
2964 /// let c: char = 'a';
2965 /// let s: String = String::from(c);
2966 /// assert_eq!("a", &s[..]);
2969 fn from(c: char) -> Self {