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};
49 #[cfg(not(no_global_oom_handling))]
50 use core::iter::FromIterator;
51 use core::iter::{from_fn, FusedIterator};
52 #[cfg(not(no_global_oom_handling))]
54 #[cfg(not(no_global_oom_handling))]
55 use core::ops::AddAssign;
56 #[cfg(not(no_global_oom_handling))]
57 use core::ops::Bound::{Excluded, Included, Unbounded};
58 use core::ops::{self, Index, IndexMut, Range, RangeBounds};
61 #[cfg(not(no_global_oom_handling))]
63 use core::str::pattern::Pattern;
65 #[cfg(not(no_global_oom_handling))]
66 use crate::borrow::{Cow, ToOwned};
67 use crate::boxed::Box;
68 use crate::collections::TryReserveError;
69 use crate::str::{self, Chars, Utf8Error};
70 #[cfg(not(no_global_oom_handling))]
71 use crate::str::{from_boxed_utf8_unchecked, FromStr};
74 /// A UTF-8–encoded, growable string.
76 /// The `String` type is the most common string type that has ownership over the
77 /// contents of the string. It has a close relationship with its borrowed
78 /// counterpart, the primitive [`str`].
82 /// You can create a `String` from [a literal string][`&str`] with [`String::from`]:
84 /// [`String::from`]: From::from
87 /// let hello = String::from("Hello, world!");
90 /// You can append a [`char`] to a `String` with the [`push`] method, and
91 /// append a [`&str`] with the [`push_str`] method:
94 /// let mut hello = String::from("Hello, ");
97 /// hello.push_str("orld!");
100 /// [`push`]: String::push
101 /// [`push_str`]: String::push_str
103 /// If you have a vector of UTF-8 bytes, you can create a `String` from it with
104 /// the [`from_utf8`] method:
107 /// // some bytes, in a vector
108 /// let sparkle_heart = vec![240, 159, 146, 150];
110 /// // We know these bytes are valid, so we'll use `unwrap()`.
111 /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
113 /// assert_eq!("💖", sparkle_heart);
116 /// [`from_utf8`]: String::from_utf8
120 /// `String`s are always valid UTF-8. This has a few implications, the first of
121 /// which is that if you need a non-UTF-8 string, consider [`OsString`]. It is
122 /// similar, but without the UTF-8 constraint. The second implication is that
123 /// you cannot index into a `String`:
125 /// ```compile_fail,E0277
128 /// println!("The first letter of s is {}", s[0]); // ERROR!!!
131 /// [`OsString`]: ../../std/ffi/struct.OsString.html "ffi::OsString"
133 /// Indexing is intended to be a constant-time operation, but UTF-8 encoding
134 /// does not allow us to do this. Furthermore, it's not clear what sort of
135 /// thing the index should return: a byte, a codepoint, or a grapheme cluster.
136 /// The [`bytes`] and [`chars`] methods return iterators over the first
137 /// two, respectively.
139 /// [`bytes`]: str::bytes
140 /// [`chars`]: str::chars
144 /// `String` implements <code>[Deref]<Target = [str]></code>, and so inherits all of [`str`]'s
145 /// methods. In addition, this means that you can pass a `String` to a
146 /// function which takes a [`&str`] by using an ampersand (`&`):
149 /// fn takes_str(s: &str) { }
151 /// let s = String::from("Hello");
156 /// This will create a [`&str`] from the `String` and pass it in. This
157 /// conversion is very inexpensive, and so generally, functions will accept
158 /// [`&str`]s as arguments unless they need a `String` for some specific
161 /// In certain cases Rust doesn't have enough information to make this
162 /// conversion, known as [`Deref`] coercion. In the following example a string
163 /// slice [`&'a str`][`&str`] implements the trait `TraitExample`, and the function
164 /// `example_func` takes anything that implements the trait. In this case Rust
165 /// would need to make two implicit conversions, which Rust doesn't have the
166 /// means to do. For that reason, the following example will not compile.
168 /// ```compile_fail,E0277
169 /// trait TraitExample {}
171 /// impl<'a> TraitExample for &'a str {}
173 /// fn example_func<A: TraitExample>(example_arg: A) {}
175 /// let example_string = String::from("example_string");
176 /// example_func(&example_string);
179 /// There are two options that would work instead. The first would be to
180 /// change the line `example_func(&example_string);` to
181 /// `example_func(example_string.as_str());`, using the method [`as_str()`]
182 /// to explicitly extract the string slice containing the string. The second
183 /// way changes `example_func(&example_string);` to
184 /// `example_func(&*example_string);`. In this case we are dereferencing a
185 /// `String` to a [`str`], then referencing the [`str`] back to
186 /// [`&str`]. The second way is more idiomatic, however both work to do the
187 /// conversion explicitly rather than relying on the implicit conversion.
191 /// A `String` is made up of three components: a pointer to some bytes, a
192 /// length, and a capacity. The pointer points to an internal buffer `String`
193 /// uses to store its data. The length is the number of bytes currently stored
194 /// in the buffer, and the capacity is the size of the buffer in bytes. As such,
195 /// the length will always be less than or equal to the capacity.
197 /// This buffer is always stored on the heap.
199 /// You can look at these with the [`as_ptr`], [`len`], and [`capacity`]
205 /// let story = String::from("Once upon a time...");
207 // FIXME Update this when vec_into_raw_parts is stabilized
208 /// // Prevent automatically dropping the String's data
209 /// let mut story = mem::ManuallyDrop::new(story);
211 /// let ptr = story.as_mut_ptr();
212 /// let len = story.len();
213 /// let capacity = story.capacity();
215 /// // story has nineteen bytes
216 /// assert_eq!(19, len);
218 /// // We can re-build a String out of ptr, len, and capacity. This is all
219 /// // unsafe because we are responsible for making sure the components are
221 /// let s = unsafe { String::from_raw_parts(ptr, len, capacity) } ;
223 /// assert_eq!(String::from("Once upon a time..."), s);
226 /// [`as_ptr`]: str::as_ptr
227 /// [`len`]: String::len
228 /// [`capacity`]: String::capacity
230 /// If a `String` has enough capacity, adding elements to it will not
231 /// re-allocate. For example, consider this program:
234 /// let mut s = String::new();
236 /// println!("{}", s.capacity());
239 /// s.push_str("hello");
240 /// println!("{}", s.capacity());
244 /// This will output the following:
255 /// At first, we have no memory allocated at all, but as we append to the
256 /// string, it increases its capacity appropriately. If we instead use the
257 /// [`with_capacity`] method to allocate the correct capacity initially:
260 /// let mut s = String::with_capacity(25);
262 /// println!("{}", s.capacity());
265 /// s.push_str("hello");
266 /// println!("{}", s.capacity());
270 /// [`with_capacity`]: String::with_capacity
272 /// We end up with a different output:
283 /// Here, there's no need to allocate more memory inside the loop.
285 /// [str]: prim@str "str"
286 /// [`str`]: prim@str "str"
287 /// [`&str`]: prim@str "&str"
288 /// [Deref]: core::ops::Deref "ops::Deref"
289 /// [`Deref`]: core::ops::Deref "ops::Deref"
290 /// [`as_str()`]: String::as_str
291 #[derive(PartialOrd, Eq, Ord)]
292 #[cfg_attr(not(test), rustc_diagnostic_item = "String")]
293 #[stable(feature = "rust1", since = "1.0.0")]
298 /// A possible error value when converting a `String` from a UTF-8 byte vector.
300 /// This type is the error type for the [`from_utf8`] method on [`String`]. It
301 /// is designed in such a way to carefully avoid reallocations: the
302 /// [`into_bytes`] method will give back the byte vector that was used in the
303 /// conversion attempt.
305 /// [`from_utf8`]: String::from_utf8
306 /// [`into_bytes`]: FromUtf8Error::into_bytes
308 /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
309 /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
310 /// an analogue to `FromUtf8Error`, and you can get one from a `FromUtf8Error`
311 /// through the [`utf8_error`] method.
313 /// [`Utf8Error`]: str::Utf8Error "std::str::Utf8Error"
314 /// [`std::str`]: core::str "std::str"
315 /// [`&str`]: prim@str "&str"
316 /// [`utf8_error`]: FromUtf8Error::utf8_error
323 /// // some invalid bytes, in a vector
324 /// let bytes = vec![0, 159];
326 /// let value = String::from_utf8(bytes);
328 /// assert!(value.is_err());
329 /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
331 #[stable(feature = "rust1", since = "1.0.0")]
332 #[cfg_attr(not(no_global_oom_handling), derive(Clone))]
333 #[derive(Debug, PartialEq, Eq)]
334 pub struct FromUtf8Error {
339 /// A possible error value when converting a `String` from a UTF-16 byte slice.
341 /// This type is the error type for the [`from_utf16`] method on [`String`].
343 /// [`from_utf16`]: String::from_utf16
349 /// // 𝄞mu<invalid>ic
350 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
351 /// 0xD800, 0x0069, 0x0063];
353 /// assert!(String::from_utf16(v).is_err());
355 #[stable(feature = "rust1", since = "1.0.0")]
357 pub struct FromUtf16Error(());
360 /// Creates a new empty `String`.
362 /// Given that the `String` is empty, this will not allocate any initial
363 /// buffer. While that means that this initial operation is very
364 /// inexpensive, it may cause excessive allocation later when you add
365 /// data. If you have an idea of how much data the `String` will hold,
366 /// consider the [`with_capacity`] method to prevent excessive
369 /// [`with_capacity`]: String::with_capacity
376 /// let s = String::new();
379 #[rustc_const_stable(feature = "const_string_new", since = "1.39.0")]
380 #[stable(feature = "rust1", since = "1.0.0")]
382 pub const fn new() -> String {
383 String { vec: Vec::new() }
386 /// Creates a new empty `String` with a particular capacity.
388 /// `String`s have an internal buffer to hold their data. The capacity is
389 /// the length of that buffer, and can be queried with the [`capacity`]
390 /// method. This method creates an empty `String`, but one with an initial
391 /// buffer that can hold `capacity` bytes. This is useful when you may be
392 /// appending a bunch of data to the `String`, reducing the number of
393 /// reallocations it needs to do.
395 /// [`capacity`]: String::capacity
397 /// If the given capacity is `0`, no allocation will occur, and this method
398 /// is identical to the [`new`] method.
400 /// [`new`]: String::new
407 /// let mut s = String::with_capacity(10);
409 /// // The String contains no chars, even though it has capacity for more
410 /// assert_eq!(s.len(), 0);
412 /// // These are all done without reallocating...
413 /// let cap = s.capacity();
418 /// assert_eq!(s.capacity(), cap);
420 /// // ...but this may make the string reallocate
423 #[cfg(not(no_global_oom_handling))]
425 #[stable(feature = "rust1", since = "1.0.0")]
427 pub fn with_capacity(capacity: usize) -> String {
428 String { vec: Vec::with_capacity(capacity) }
431 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
432 // required for this method definition, is not available. Since we don't
433 // require this method for testing purposes, I'll just stub it
434 // NB see the slice::hack module in slice.rs for more information
437 pub fn from_str(_: &str) -> String {
438 panic!("not available with cfg(test)");
441 /// Converts a vector of bytes to a `String`.
443 /// A string ([`String`]) is made of bytes ([`u8`]), and a vector of bytes
444 /// ([`Vec<u8>`]) is made of bytes, so this function converts between the
445 /// two. Not all byte slices are valid `String`s, however: `String`
446 /// requires that it is valid UTF-8. `from_utf8()` checks to ensure that
447 /// the bytes are valid UTF-8, and then does the conversion.
449 /// If you are sure that the byte slice is valid UTF-8, and you don't want
450 /// to incur the overhead of the validity check, there is an unsafe version
451 /// of this function, [`from_utf8_unchecked`], which has the same behavior
452 /// but skips the check.
454 /// This method will take care to not copy the vector, for efficiency's
457 /// If you need a [`&str`] instead of a `String`, consider
458 /// [`str::from_utf8`].
460 /// The inverse of this method is [`into_bytes`].
464 /// Returns [`Err`] if the slice is not UTF-8 with a description as to why the
465 /// provided bytes are not UTF-8. The vector you moved in is also included.
472 /// // some bytes, in a vector
473 /// let sparkle_heart = vec![240, 159, 146, 150];
475 /// // We know these bytes are valid, so we'll use `unwrap()`.
476 /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
478 /// assert_eq!("💖", sparkle_heart);
484 /// // some invalid bytes, in a vector
485 /// let sparkle_heart = vec![0, 159, 146, 150];
487 /// assert!(String::from_utf8(sparkle_heart).is_err());
490 /// See the docs for [`FromUtf8Error`] for more details on what you can do
493 /// [`from_utf8_unchecked`]: String::from_utf8_unchecked
494 /// [`Vec<u8>`]: crate::vec::Vec "Vec"
495 /// [`&str`]: prim@str "&str"
496 /// [`into_bytes`]: String::into_bytes
498 #[stable(feature = "rust1", since = "1.0.0")]
499 pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error> {
500 match str::from_utf8(&vec) {
501 Ok(..) => Ok(String { vec }),
502 Err(e) => Err(FromUtf8Error { bytes: vec, error: e }),
506 /// Converts a slice of bytes to a string, including invalid characters.
508 /// Strings are made of bytes ([`u8`]), and a slice of bytes
509 /// ([`&[u8]`][byteslice]) is made of bytes, so this function converts
510 /// between the two. Not all byte slices are valid strings, however: strings
511 /// are required to be valid UTF-8. During this conversion,
512 /// `from_utf8_lossy()` will replace any invalid UTF-8 sequences with
513 /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD], which looks like this: �
515 /// [byteslice]: prim@slice
516 /// [U+FFFD]: core::char::REPLACEMENT_CHARACTER
518 /// If you are sure that the byte slice is valid UTF-8, and you don't want
519 /// to incur the overhead of the conversion, there is an unsafe version
520 /// of this function, [`from_utf8_unchecked`], which has the same behavior
521 /// but skips the checks.
523 /// [`from_utf8_unchecked`]: String::from_utf8_unchecked
525 /// This function returns a [`Cow<'a, str>`]. If our byte slice is invalid
526 /// UTF-8, then we need to insert the replacement characters, which will
527 /// change the size of the string, and hence, require a `String`. But if
528 /// it's already valid UTF-8, we don't need a new allocation. This return
529 /// type allows us to handle both cases.
531 /// [`Cow<'a, str>`]: crate::borrow::Cow "borrow::Cow"
538 /// // some bytes, in a vector
539 /// let sparkle_heart = vec![240, 159, 146, 150];
541 /// let sparkle_heart = String::from_utf8_lossy(&sparkle_heart);
543 /// assert_eq!("💖", sparkle_heart);
549 /// // some invalid bytes
550 /// let input = b"Hello \xF0\x90\x80World";
551 /// let output = String::from_utf8_lossy(input);
553 /// assert_eq!("Hello �World", output);
556 #[cfg(not(no_global_oom_handling))]
557 #[stable(feature = "rust1", since = "1.0.0")]
558 pub fn from_utf8_lossy(v: &[u8]) -> Cow<'_, str> {
559 let mut iter = lossy::Utf8Lossy::from_bytes(v).chunks();
561 let first_valid = if let Some(chunk) = iter.next() {
562 let lossy::Utf8LossyChunk { valid, broken } = chunk;
563 if broken.is_empty() {
564 debug_assert_eq!(valid.len(), v.len());
565 return Cow::Borrowed(valid);
569 return Cow::Borrowed("");
572 const REPLACEMENT: &str = "\u{FFFD}";
574 let mut res = String::with_capacity(v.len());
575 res.push_str(first_valid);
576 res.push_str(REPLACEMENT);
578 for lossy::Utf8LossyChunk { valid, broken } in iter {
580 if !broken.is_empty() {
581 res.push_str(REPLACEMENT);
588 /// Decode a UTF-16–encoded vector `v` into a `String`, returning [`Err`]
589 /// if `v` contains any invalid data.
597 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
598 /// 0x0073, 0x0069, 0x0063];
599 /// assert_eq!(String::from("𝄞music"),
600 /// String::from_utf16(v).unwrap());
602 /// // 𝄞mu<invalid>ic
603 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
604 /// 0xD800, 0x0069, 0x0063];
605 /// assert!(String::from_utf16(v).is_err());
607 #[cfg(not(no_global_oom_handling))]
608 #[stable(feature = "rust1", since = "1.0.0")]
609 pub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error> {
610 // This isn't done via collect::<Result<_, _>>() for performance reasons.
611 // FIXME: the function can be simplified again when #48994 is closed.
612 let mut ret = String::with_capacity(v.len());
613 for c in decode_utf16(v.iter().cloned()) {
617 return Err(FromUtf16Error(()));
623 /// Decode a UTF-16–encoded slice `v` into a `String`, replacing
624 /// invalid data with [the replacement character (`U+FFFD`)][U+FFFD].
626 /// Unlike [`from_utf8_lossy`] which returns a [`Cow<'a, str>`],
627 /// `from_utf16_lossy` returns a `String` since the UTF-16 to UTF-8
628 /// conversion requires a memory allocation.
630 /// [`from_utf8_lossy`]: String::from_utf8_lossy
631 /// [`Cow<'a, str>`]: crate::borrow::Cow "borrow::Cow"
632 /// [U+FFFD]: core::char::REPLACEMENT_CHARACTER
639 /// // 𝄞mus<invalid>ic<invalid>
640 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
641 /// 0x0073, 0xDD1E, 0x0069, 0x0063,
644 /// assert_eq!(String::from("𝄞mus\u{FFFD}ic\u{FFFD}"),
645 /// String::from_utf16_lossy(v));
647 #[cfg(not(no_global_oom_handling))]
650 #[stable(feature = "rust1", since = "1.0.0")]
651 pub fn from_utf16_lossy(v: &[u16]) -> String {
652 decode_utf16(v.iter().cloned()).map(|r| r.unwrap_or(REPLACEMENT_CHARACTER)).collect()
655 /// Decomposes a `String` into its raw components.
657 /// Returns the raw pointer to the underlying data, the length of
658 /// the string (in bytes), and the allocated capacity of the data
659 /// (in bytes). These are the same arguments in the same order as
660 /// the arguments to [`from_raw_parts`].
662 /// After calling this function, the caller is responsible for the
663 /// memory previously managed by the `String`. The only way to do
664 /// this is to convert the raw pointer, length, and capacity back
665 /// into a `String` with the [`from_raw_parts`] function, allowing
666 /// the destructor to perform the cleanup.
668 /// [`from_raw_parts`]: String::from_raw_parts
673 /// #![feature(vec_into_raw_parts)]
674 /// let s = String::from("hello");
676 /// let (ptr, len, cap) = s.into_raw_parts();
678 /// let rebuilt = unsafe { String::from_raw_parts(ptr, len, cap) };
679 /// assert_eq!(rebuilt, "hello");
681 #[must_use = "`self` will be dropped if the result is not used"]
682 #[unstable(feature = "vec_into_raw_parts", reason = "new API", issue = "65816")]
683 pub fn into_raw_parts(self) -> (*mut u8, usize, usize) {
684 self.vec.into_raw_parts()
687 /// Creates a new `String` from a length, capacity, and pointer.
691 /// This is highly unsafe, due to the number of invariants that aren't
694 /// * The memory at `buf` needs to have been previously allocated by the
695 /// same allocator the standard library uses, with a required alignment of exactly 1.
696 /// * `length` needs to be less than or equal to `capacity`.
697 /// * `capacity` needs to be the correct value.
698 /// * The first `length` bytes at `buf` need to be valid UTF-8.
700 /// Violating these may cause problems like corrupting the allocator's
701 /// internal data structures.
703 /// The ownership of `buf` is effectively transferred to the
704 /// `String` which may then deallocate, reallocate or change the
705 /// contents of memory pointed to by the pointer at will. Ensure
706 /// that nothing else uses the pointer after calling this
717 /// let s = String::from("hello");
719 // FIXME Update this when vec_into_raw_parts is stabilized
720 /// // Prevent automatically dropping the String's data
721 /// let mut s = mem::ManuallyDrop::new(s);
723 /// let ptr = s.as_mut_ptr();
724 /// let len = s.len();
725 /// let capacity = s.capacity();
727 /// let s = String::from_raw_parts(ptr, len, capacity);
729 /// assert_eq!(String::from("hello"), s);
733 #[stable(feature = "rust1", since = "1.0.0")]
734 pub unsafe fn from_raw_parts(buf: *mut u8, length: usize, capacity: usize) -> String {
735 unsafe { String { vec: Vec::from_raw_parts(buf, length, capacity) } }
738 /// Converts a vector of bytes to a `String` without checking that the
739 /// string contains valid UTF-8.
741 /// See the safe version, [`from_utf8`], for more details.
743 /// [`from_utf8`]: String::from_utf8
747 /// This function is unsafe because it does not check that the bytes passed
748 /// to it are valid UTF-8. If this constraint is violated, it may cause
749 /// memory unsafety issues with future users of the `String`, as the rest of
750 /// the standard library assumes that `String`s are valid UTF-8.
757 /// // some bytes, in a vector
758 /// let sparkle_heart = vec![240, 159, 146, 150];
760 /// let sparkle_heart = unsafe {
761 /// String::from_utf8_unchecked(sparkle_heart)
764 /// assert_eq!("💖", sparkle_heart);
768 #[stable(feature = "rust1", since = "1.0.0")]
769 pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String {
770 String { vec: bytes }
773 /// Converts a `String` into a byte vector.
775 /// This consumes the `String`, so we do not need to copy its contents.
782 /// let s = String::from("hello");
783 /// let bytes = s.into_bytes();
785 /// assert_eq!(&[104, 101, 108, 108, 111][..], &bytes[..]);
788 #[must_use = "`self` will be dropped if the result is not used"]
789 #[stable(feature = "rust1", since = "1.0.0")]
790 pub fn into_bytes(self) -> Vec<u8> {
794 /// Extracts a string slice containing the entire `String`.
801 /// let s = String::from("foo");
803 /// assert_eq!("foo", s.as_str());
807 #[stable(feature = "string_as_str", since = "1.7.0")]
808 pub fn as_str(&self) -> &str {
812 /// Converts a `String` into a mutable string slice.
819 /// let mut s = String::from("foobar");
820 /// let s_mut_str = s.as_mut_str();
822 /// s_mut_str.make_ascii_uppercase();
824 /// assert_eq!("FOOBAR", s_mut_str);
828 #[stable(feature = "string_as_str", since = "1.7.0")]
829 pub fn as_mut_str(&mut self) -> &mut str {
833 /// Appends a given string slice onto the end of this `String`.
840 /// let mut s = String::from("foo");
842 /// s.push_str("bar");
844 /// assert_eq!("foobar", s);
846 #[cfg(not(no_global_oom_handling))]
848 #[stable(feature = "rust1", since = "1.0.0")]
849 pub fn push_str(&mut self, string: &str) {
850 self.vec.extend_from_slice(string.as_bytes())
853 /// Copies elements from `src` range to the end of the string.
857 /// Panics if the starting point or end point do not lie on a [`char`]
858 /// boundary, or if they're out of bounds.
863 /// #![feature(string_extend_from_within)]
864 /// let mut string = String::from("abcde");
866 /// string.extend_from_within(2..);
867 /// assert_eq!(string, "abcdecde");
869 /// string.extend_from_within(..2);
870 /// assert_eq!(string, "abcdecdeab");
872 /// string.extend_from_within(4..8);
873 /// assert_eq!(string, "abcdecdeabecde");
875 #[cfg(not(no_global_oom_handling))]
876 #[unstable(feature = "string_extend_from_within", issue = "none")]
877 pub fn extend_from_within<R>(&mut self, src: R)
879 R: RangeBounds<usize>,
881 let src @ Range { start, end } = slice::range(src, ..self.len());
883 assert!(self.is_char_boundary(start));
884 assert!(self.is_char_boundary(end));
886 self.vec.extend_from_within(src);
889 /// Returns this `String`'s capacity, in bytes.
896 /// let s = String::with_capacity(10);
898 /// assert!(s.capacity() >= 10);
902 #[stable(feature = "rust1", since = "1.0.0")]
903 pub fn capacity(&self) -> usize {
907 /// Ensures that this `String`'s capacity is at least `additional` bytes
908 /// larger than its length.
910 /// The capacity may be increased by more than `additional` bytes if it
911 /// chooses, to prevent frequent reallocations.
913 /// If you do not want this "at least" behavior, see the [`reserve_exact`]
918 /// Panics if the new capacity overflows [`usize`].
920 /// [`reserve_exact`]: String::reserve_exact
927 /// let mut s = String::new();
931 /// assert!(s.capacity() >= 10);
934 /// This might not actually increase the capacity:
937 /// let mut s = String::with_capacity(10);
941 /// // s now has a length of 2 and a capacity of 10
942 /// assert_eq!(2, s.len());
943 /// assert_eq!(10, s.capacity());
945 /// // Since we already have an extra 8 capacity, calling this...
948 /// // ... doesn't actually increase.
949 /// assert_eq!(10, s.capacity());
951 #[cfg(not(no_global_oom_handling))]
953 #[stable(feature = "rust1", since = "1.0.0")]
954 pub fn reserve(&mut self, additional: usize) {
955 self.vec.reserve(additional)
958 /// Ensures that this `String`'s capacity is `additional` bytes
959 /// larger than its length.
961 /// Consider using the [`reserve`] method unless you absolutely know
962 /// better than the allocator.
964 /// [`reserve`]: String::reserve
968 /// Panics if the new capacity overflows `usize`.
975 /// let mut s = String::new();
977 /// s.reserve_exact(10);
979 /// assert!(s.capacity() >= 10);
982 /// This might not actually increase the capacity:
985 /// let mut s = String::with_capacity(10);
989 /// // s now has a length of 2 and a capacity of 10
990 /// assert_eq!(2, s.len());
991 /// assert_eq!(10, s.capacity());
993 /// // Since we already have an extra 8 capacity, calling this...
994 /// s.reserve_exact(8);
996 /// // ... doesn't actually increase.
997 /// assert_eq!(10, s.capacity());
999 #[cfg(not(no_global_oom_handling))]
1001 #[stable(feature = "rust1", since = "1.0.0")]
1002 pub fn reserve_exact(&mut self, additional: usize) {
1003 self.vec.reserve_exact(additional)
1006 /// Tries to reserve capacity for at least `additional` more elements to be inserted
1007 /// in the given `String`. The collection may reserve more space to avoid
1008 /// frequent reallocations. After calling `reserve`, capacity will be
1009 /// greater than or equal to `self.len() + additional`. Does nothing if
1010 /// capacity is already sufficient.
1014 /// If the capacity overflows, or the allocator reports a failure, then an error
1020 /// use std::collections::TryReserveError;
1022 /// fn process_data(data: &str) -> Result<String, TryReserveError> {
1023 /// let mut output = String::new();
1025 /// // Pre-reserve the memory, exiting if we can't
1026 /// output.try_reserve(data.len())?;
1028 /// // Now we know this can't OOM in the middle of our complex work
1029 /// output.push_str(data);
1033 /// # process_data("rust").expect("why is the test harness OOMing on 4 bytes?");
1035 #[stable(feature = "try_reserve", since = "1.57.0")]
1036 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
1037 self.vec.try_reserve(additional)
1040 /// Tries to reserve the minimum capacity for exactly `additional` more elements to
1041 /// be inserted in the given `String`. After calling `reserve_exact`,
1042 /// capacity will be greater than or equal to `self.len() + additional`.
1043 /// Does nothing if the capacity is already sufficient.
1045 /// Note that the allocator may give the collection more space than it
1046 /// requests. Therefore, capacity can not be relied upon to be precisely
1047 /// minimal. Prefer [`try_reserve`] if future insertions are expected.
1049 /// [`try_reserve`]: String::try_reserve
1053 /// If the capacity overflows, or the allocator reports a failure, then an error
1059 /// use std::collections::TryReserveError;
1061 /// fn process_data(data: &str) -> Result<String, TryReserveError> {
1062 /// let mut output = String::new();
1064 /// // Pre-reserve the memory, exiting if we can't
1065 /// output.try_reserve(data.len())?;
1067 /// // Now we know this can't OOM in the middle of our complex work
1068 /// output.push_str(data);
1072 /// # process_data("rust").expect("why is the test harness OOMing on 4 bytes?");
1074 #[stable(feature = "try_reserve", since = "1.57.0")]
1075 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
1076 self.vec.try_reserve_exact(additional)
1079 /// Shrinks the capacity of this `String` to match its length.
1086 /// let mut s = String::from("foo");
1089 /// assert!(s.capacity() >= 100);
1091 /// s.shrink_to_fit();
1092 /// assert_eq!(3, s.capacity());
1094 #[cfg(not(no_global_oom_handling))]
1096 #[stable(feature = "rust1", since = "1.0.0")]
1097 pub fn shrink_to_fit(&mut self) {
1098 self.vec.shrink_to_fit()
1101 /// Shrinks the capacity of this `String` with a lower bound.
1103 /// The capacity will remain at least as large as both the length
1104 /// and the supplied value.
1106 /// If the current capacity is less than the lower limit, this is a no-op.
1111 /// let mut s = String::from("foo");
1114 /// assert!(s.capacity() >= 100);
1116 /// s.shrink_to(10);
1117 /// assert!(s.capacity() >= 10);
1119 /// assert!(s.capacity() >= 3);
1121 #[cfg(not(no_global_oom_handling))]
1123 #[stable(feature = "shrink_to", since = "1.56.0")]
1124 pub fn shrink_to(&mut self, min_capacity: usize) {
1125 self.vec.shrink_to(min_capacity)
1128 /// Appends the given [`char`] to the end of this `String`.
1135 /// let mut s = String::from("abc");
1141 /// assert_eq!("abc123", s);
1143 #[cfg(not(no_global_oom_handling))]
1145 #[stable(feature = "rust1", since = "1.0.0")]
1146 pub fn push(&mut self, ch: char) {
1147 match ch.len_utf8() {
1148 1 => self.vec.push(ch as u8),
1149 _ => self.vec.extend_from_slice(ch.encode_utf8(&mut [0; 4]).as_bytes()),
1153 /// Returns a byte slice of this `String`'s contents.
1155 /// The inverse of this method is [`from_utf8`].
1157 /// [`from_utf8`]: String::from_utf8
1164 /// let s = String::from("hello");
1166 /// assert_eq!(&[104, 101, 108, 108, 111], s.as_bytes());
1170 #[stable(feature = "rust1", since = "1.0.0")]
1171 pub fn as_bytes(&self) -> &[u8] {
1175 /// Shortens this `String` to the specified length.
1177 /// If `new_len` is greater than the string's current length, this has no
1180 /// Note that this method has no effect on the allocated capacity
1185 /// Panics if `new_len` does not lie on a [`char`] boundary.
1192 /// let mut s = String::from("hello");
1196 /// assert_eq!("he", s);
1199 #[stable(feature = "rust1", since = "1.0.0")]
1200 pub fn truncate(&mut self, new_len: usize) {
1201 if new_len <= self.len() {
1202 assert!(self.is_char_boundary(new_len));
1203 self.vec.truncate(new_len)
1207 /// Removes the last character from the string buffer and returns it.
1209 /// Returns [`None`] if this `String` is empty.
1216 /// let mut s = String::from("foo");
1218 /// assert_eq!(s.pop(), Some('o'));
1219 /// assert_eq!(s.pop(), Some('o'));
1220 /// assert_eq!(s.pop(), Some('f'));
1222 /// assert_eq!(s.pop(), None);
1225 #[stable(feature = "rust1", since = "1.0.0")]
1226 pub fn pop(&mut self) -> Option<char> {
1227 let ch = self.chars().rev().next()?;
1228 let newlen = self.len() - ch.len_utf8();
1230 self.vec.set_len(newlen);
1235 /// Removes a [`char`] from this `String` at a byte position and returns it.
1237 /// This is an *O*(*n*) operation, as it requires copying every element in the
1242 /// Panics if `idx` is larger than or equal to the `String`'s length,
1243 /// or if it does not lie on a [`char`] boundary.
1250 /// let mut s = String::from("foo");
1252 /// assert_eq!(s.remove(0), 'f');
1253 /// assert_eq!(s.remove(1), 'o');
1254 /// assert_eq!(s.remove(0), 'o');
1257 #[stable(feature = "rust1", since = "1.0.0")]
1258 pub fn remove(&mut self, idx: usize) -> char {
1259 let ch = match self[idx..].chars().next() {
1261 None => panic!("cannot remove a char from the end of a string"),
1264 let next = idx + ch.len_utf8();
1265 let len = self.len();
1267 ptr::copy(self.vec.as_ptr().add(next), self.vec.as_mut_ptr().add(idx), len - next);
1268 self.vec.set_len(len - (next - idx));
1273 /// Remove all matches of pattern `pat` in the `String`.
1278 /// #![feature(string_remove_matches)]
1279 /// let mut s = String::from("Trees are not green, the sky is not blue.");
1280 /// s.remove_matches("not ");
1281 /// assert_eq!("Trees are green, the sky is blue.", s);
1284 /// Matches will be detected and removed iteratively, so in cases where
1285 /// patterns overlap, only the first pattern will be removed:
1288 /// #![feature(string_remove_matches)]
1289 /// let mut s = String::from("banana");
1290 /// s.remove_matches("ana");
1291 /// assert_eq!("bna", s);
1293 #[cfg(not(no_global_oom_handling))]
1294 #[unstable(feature = "string_remove_matches", reason = "new API", issue = "72826")]
1295 pub fn remove_matches<'a, P>(&'a mut self, pat: P)
1297 P: for<'x> Pattern<'x>,
1299 use core::str::pattern::Searcher;
1302 let mut searcher = pat.into_searcher(self);
1303 // Per Searcher::next:
1305 // A Match result needs to contain the whole matched pattern,
1306 // however Reject results may be split up into arbitrary many
1307 // adjacent fragments. Both ranges may have zero length.
1309 // In practice the implementation of Searcher::next_match tends to
1310 // be more efficient, so we use it here and do some work to invert
1311 // matches into rejections since that's what we want to copy below.
1313 let rejections: Vec<_> = from_fn(|| {
1314 let (start, end) = searcher.next_match()?;
1315 let prev_front = front;
1317 Some((prev_front, start))
1320 rejections.into_iter().chain(core::iter::once((front, self.len())))
1324 let ptr = self.vec.as_mut_ptr();
1326 for (start, end) in rejections {
1327 let count = end - start;
1329 // SAFETY: per Searcher::next:
1331 // The stream of Match and Reject values up to a Done will
1332 // contain index ranges that are adjacent, non-overlapping,
1333 // covering the whole haystack, and laying on utf8
1336 ptr::copy(ptr.add(start), ptr.add(len), count);
1343 self.vec.set_len(len);
1347 /// Retains only the characters specified by the predicate.
1349 /// In other words, remove all characters `c` such that `f(c)` returns `false`.
1350 /// This method operates in place, visiting each character exactly once in the
1351 /// original order, and preserves the order of the retained characters.
1356 /// let mut s = String::from("f_o_ob_ar");
1358 /// s.retain(|c| c != '_');
1360 /// assert_eq!(s, "foobar");
1363 /// Because the elements are visited exactly once in the original order,
1364 /// external state may be used to decide which elements to keep.
1367 /// let mut s = String::from("abcde");
1368 /// let keep = [false, true, true, false, true];
1369 /// let mut iter = keep.iter();
1370 /// s.retain(|_| *iter.next().unwrap());
1371 /// assert_eq!(s, "bce");
1374 #[stable(feature = "string_retain", since = "1.26.0")]
1375 pub fn retain<F>(&mut self, mut f: F)
1377 F: FnMut(char) -> bool,
1379 struct SetLenOnDrop<'a> {
1385 impl<'a> Drop for SetLenOnDrop<'a> {
1386 fn drop(&mut self) {
1387 let new_len = self.idx - self.del_bytes;
1388 debug_assert!(new_len <= self.s.len());
1389 unsafe { self.s.vec.set_len(new_len) };
1393 let len = self.len();
1394 let mut guard = SetLenOnDrop { s: self, idx: 0, del_bytes: 0 };
1396 while guard.idx < len {
1397 let ch = unsafe { guard.s.get_unchecked(guard.idx..len).chars().next().unwrap() };
1398 let ch_len = ch.len_utf8();
1401 guard.del_bytes += ch_len;
1402 } else if guard.del_bytes > 0 {
1405 guard.s.vec.as_ptr().add(guard.idx),
1406 guard.s.vec.as_mut_ptr().add(guard.idx - guard.del_bytes),
1412 // Point idx to the next char
1413 guard.idx += ch_len;
1419 /// Inserts a character into this `String` at a byte position.
1421 /// This is an *O*(*n*) operation as it requires copying every element in the
1426 /// Panics if `idx` is larger than the `String`'s length, or if it does not
1427 /// lie on a [`char`] boundary.
1434 /// let mut s = String::with_capacity(3);
1436 /// s.insert(0, 'f');
1437 /// s.insert(1, 'o');
1438 /// s.insert(2, 'o');
1440 /// assert_eq!("foo", s);
1442 #[cfg(not(no_global_oom_handling))]
1444 #[stable(feature = "rust1", since = "1.0.0")]
1445 pub fn insert(&mut self, idx: usize, ch: char) {
1446 assert!(self.is_char_boundary(idx));
1447 let mut bits = [0; 4];
1448 let bits = ch.encode_utf8(&mut bits).as_bytes();
1451 self.insert_bytes(idx, bits);
1455 #[cfg(not(no_global_oom_handling))]
1456 unsafe fn insert_bytes(&mut self, idx: usize, bytes: &[u8]) {
1457 let len = self.len();
1458 let amt = bytes.len();
1459 self.vec.reserve(amt);
1462 ptr::copy(self.vec.as_ptr().add(idx), self.vec.as_mut_ptr().add(idx + amt), len - idx);
1463 ptr::copy_nonoverlapping(bytes.as_ptr(), self.vec.as_mut_ptr().add(idx), amt);
1464 self.vec.set_len(len + amt);
1468 /// Inserts a string slice into this `String` at a byte position.
1470 /// This is an *O*(*n*) operation as it requires copying every element in the
1475 /// Panics if `idx` is larger than the `String`'s length, or if it does not
1476 /// lie on a [`char`] boundary.
1483 /// let mut s = String::from("bar");
1485 /// s.insert_str(0, "foo");
1487 /// assert_eq!("foobar", s);
1489 #[cfg(not(no_global_oom_handling))]
1491 #[stable(feature = "insert_str", since = "1.16.0")]
1492 pub fn insert_str(&mut self, idx: usize, string: &str) {
1493 assert!(self.is_char_boundary(idx));
1496 self.insert_bytes(idx, string.as_bytes());
1500 /// Returns a mutable reference to the contents of this `String`.
1504 /// This function is unsafe because the returned `&mut Vec` allows writing
1505 /// bytes which are not valid UTF-8. If this constraint is violated, using
1506 /// the original `String` after dropping the `&mut Vec` may violate memory
1507 /// safety, as the rest of the standard library assumes that `String`s are
1515 /// let mut s = String::from("hello");
1518 /// let vec = s.as_mut_vec();
1519 /// assert_eq!(&[104, 101, 108, 108, 111][..], &vec[..]);
1523 /// assert_eq!(s, "olleh");
1526 #[stable(feature = "rust1", since = "1.0.0")]
1527 pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1531 /// Returns the length of this `String`, in bytes, not [`char`]s or
1532 /// graphemes. In other words, it might not be what a human considers the
1533 /// length of the string.
1540 /// let a = String::from("foo");
1541 /// assert_eq!(a.len(), 3);
1543 /// let fancy_f = String::from("ƒoo");
1544 /// assert_eq!(fancy_f.len(), 4);
1545 /// assert_eq!(fancy_f.chars().count(), 3);
1549 #[stable(feature = "rust1", since = "1.0.0")]
1550 pub fn len(&self) -> usize {
1554 /// Returns `true` if this `String` has a length of zero, and `false` otherwise.
1561 /// let mut v = String::new();
1562 /// assert!(v.is_empty());
1565 /// assert!(!v.is_empty());
1569 #[stable(feature = "rust1", since = "1.0.0")]
1570 pub fn is_empty(&self) -> bool {
1574 /// Splits the string into two at the given byte index.
1576 /// Returns a newly allocated `String`. `self` contains bytes `[0, at)`, and
1577 /// the returned `String` contains bytes `[at, len)`. `at` must be on the
1578 /// boundary of a UTF-8 code point.
1580 /// Note that the capacity of `self` does not change.
1584 /// Panics if `at` is not on a `UTF-8` code point boundary, or if it is beyond the last
1585 /// code point of the string.
1591 /// let mut hello = String::from("Hello, World!");
1592 /// let world = hello.split_off(7);
1593 /// assert_eq!(hello, "Hello, ");
1594 /// assert_eq!(world, "World!");
1597 #[cfg(not(no_global_oom_handling))]
1599 #[stable(feature = "string_split_off", since = "1.16.0")]
1600 #[must_use = "use `.truncate()` if you don't need the other half"]
1601 pub fn split_off(&mut self, at: usize) -> String {
1602 assert!(self.is_char_boundary(at));
1603 let other = self.vec.split_off(at);
1604 unsafe { String::from_utf8_unchecked(other) }
1607 /// Truncates this `String`, removing all contents.
1609 /// While this means the `String` will have a length of zero, it does not
1610 /// touch its capacity.
1617 /// let mut s = String::from("foo");
1621 /// assert!(s.is_empty());
1622 /// assert_eq!(0, s.len());
1623 /// assert_eq!(3, s.capacity());
1626 #[stable(feature = "rust1", since = "1.0.0")]
1627 pub fn clear(&mut self) {
1631 /// Creates a draining iterator that removes the specified range in the `String`
1632 /// and yields the removed `chars`.
1634 /// Note: The element range is removed even if the iterator is not
1635 /// consumed until the end.
1639 /// Panics if the starting point or end point do not lie on a [`char`]
1640 /// boundary, or if they're out of bounds.
1647 /// let mut s = String::from("α is alpha, β is beta");
1648 /// let beta_offset = s.find('β').unwrap_or(s.len());
1650 /// // Remove the range up until the β from the string
1651 /// let t: String = s.drain(..beta_offset).collect();
1652 /// assert_eq!(t, "α is alpha, ");
1653 /// assert_eq!(s, "β is beta");
1655 /// // A full range clears the string
1657 /// assert_eq!(s, "");
1659 #[stable(feature = "drain", since = "1.6.0")]
1660 pub fn drain<R>(&mut self, range: R) -> Drain<'_>
1662 R: RangeBounds<usize>,
1666 // The String version of Drain does not have the memory safety issues
1667 // of the vector version. The data is just plain bytes.
1668 // Because the range removal happens in Drop, if the Drain iterator is leaked,
1669 // the removal will not happen.
1670 let Range { start, end } = slice::range(range, ..self.len());
1671 assert!(self.is_char_boundary(start));
1672 assert!(self.is_char_boundary(end));
1674 // Take out two simultaneous borrows. The &mut String won't be accessed
1675 // until iteration is over, in Drop.
1676 let self_ptr = self as *mut _;
1677 // SAFETY: `slice::range` and `is_char_boundary` do the appropriate bounds checks.
1678 let chars_iter = unsafe { self.get_unchecked(start..end) }.chars();
1680 Drain { start, end, iter: chars_iter, string: self_ptr }
1683 /// Removes the specified range in the string,
1684 /// and replaces it with the given string.
1685 /// The given string doesn't need to be the same length as the range.
1689 /// Panics if the starting point or end point do not lie on a [`char`]
1690 /// boundary, or if they're out of bounds.
1697 /// let mut s = String::from("α is alpha, β is beta");
1698 /// let beta_offset = s.find('β').unwrap_or(s.len());
1700 /// // Replace the range up until the β from the string
1701 /// s.replace_range(..beta_offset, "Α is capital alpha; ");
1702 /// assert_eq!(s, "Α is capital alpha; β is beta");
1704 #[cfg(not(no_global_oom_handling))]
1705 #[stable(feature = "splice", since = "1.27.0")]
1706 pub fn replace_range<R>(&mut self, range: R, replace_with: &str)
1708 R: RangeBounds<usize>,
1712 // Replace_range does not have the memory safety issues of a vector Splice.
1713 // of the vector version. The data is just plain bytes.
1715 // WARNING: Inlining this variable would be unsound (#81138)
1716 let start = range.start_bound();
1718 Included(&n) => assert!(self.is_char_boundary(n)),
1719 Excluded(&n) => assert!(self.is_char_boundary(n + 1)),
1722 // WARNING: Inlining this variable would be unsound (#81138)
1723 let end = range.end_bound();
1725 Included(&n) => assert!(self.is_char_boundary(n + 1)),
1726 Excluded(&n) => assert!(self.is_char_boundary(n)),
1730 // Using `range` again would be unsound (#81138)
1731 // We assume the bounds reported by `range` remain the same, but
1732 // an adversarial implementation could change between calls
1733 unsafe { self.as_mut_vec() }.splice((start, end), replace_with.bytes());
1736 /// Converts this `String` into a <code>[Box]<[str]></code>.
1738 /// This will drop any excess capacity.
1740 /// [str]: prim@str "str"
1747 /// let s = String::from("hello");
1749 /// let b = s.into_boxed_str();
1751 #[cfg(not(no_global_oom_handling))]
1752 #[stable(feature = "box_str", since = "1.4.0")]
1753 #[must_use = "`self` will be dropped if the result is not used"]
1755 pub fn into_boxed_str(self) -> Box<str> {
1756 let slice = self.vec.into_boxed_slice();
1757 unsafe { from_boxed_utf8_unchecked(slice) }
1761 impl FromUtf8Error {
1762 /// Returns a slice of [`u8`]s bytes that were attempted to convert to a `String`.
1769 /// // some invalid bytes, in a vector
1770 /// let bytes = vec![0, 159];
1772 /// let value = String::from_utf8(bytes);
1774 /// assert_eq!(&[0, 159], value.unwrap_err().as_bytes());
1777 #[stable(feature = "from_utf8_error_as_bytes", since = "1.26.0")]
1778 pub fn as_bytes(&self) -> &[u8] {
1782 /// Returns the bytes that were attempted to convert to a `String`.
1784 /// This method is carefully constructed to avoid allocation. It will
1785 /// consume the error, moving out the bytes, so that a copy of the bytes
1786 /// does not need to be made.
1793 /// // some invalid bytes, in a vector
1794 /// let bytes = vec![0, 159];
1796 /// let value = String::from_utf8(bytes);
1798 /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
1800 #[must_use = "`self` will be dropped if the result is not used"]
1801 #[stable(feature = "rust1", since = "1.0.0")]
1802 pub fn into_bytes(self) -> Vec<u8> {
1806 /// Fetch a `Utf8Error` to get more details about the conversion failure.
1808 /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
1809 /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
1810 /// an analogue to `FromUtf8Error`. See its documentation for more details
1813 /// [`std::str`]: core::str "std::str"
1814 /// [`&str`]: prim@str "&str"
1821 /// // some invalid bytes, in a vector
1822 /// let bytes = vec![0, 159];
1824 /// let error = String::from_utf8(bytes).unwrap_err().utf8_error();
1826 /// // the first byte is invalid here
1827 /// assert_eq!(1, error.valid_up_to());
1830 #[stable(feature = "rust1", since = "1.0.0")]
1831 pub fn utf8_error(&self) -> Utf8Error {
1836 #[stable(feature = "rust1", since = "1.0.0")]
1837 impl fmt::Display for FromUtf8Error {
1838 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1839 fmt::Display::fmt(&self.error, f)
1843 #[stable(feature = "rust1", since = "1.0.0")]
1844 impl fmt::Display for FromUtf16Error {
1845 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1846 fmt::Display::fmt("invalid utf-16: lone surrogate found", f)
1850 #[cfg(not(no_global_oom_handling))]
1851 #[stable(feature = "rust1", since = "1.0.0")]
1852 impl Clone for String {
1853 fn clone(&self) -> Self {
1854 String { vec: self.vec.clone() }
1857 fn clone_from(&mut self, source: &Self) {
1858 self.vec.clone_from(&source.vec);
1862 #[cfg(not(no_global_oom_handling))]
1863 #[stable(feature = "rust1", since = "1.0.0")]
1864 impl FromIterator<char> for String {
1865 fn from_iter<I: IntoIterator<Item = char>>(iter: I) -> String {
1866 let mut buf = String::new();
1872 #[cfg(not(no_global_oom_handling))]
1873 #[stable(feature = "string_from_iter_by_ref", since = "1.17.0")]
1874 impl<'a> FromIterator<&'a char> for String {
1875 fn from_iter<I: IntoIterator<Item = &'a char>>(iter: I) -> String {
1876 let mut buf = String::new();
1882 #[cfg(not(no_global_oom_handling))]
1883 #[stable(feature = "rust1", since = "1.0.0")]
1884 impl<'a> FromIterator<&'a str> for String {
1885 fn from_iter<I: IntoIterator<Item = &'a str>>(iter: I) -> String {
1886 let mut buf = String::new();
1892 #[cfg(not(no_global_oom_handling))]
1893 #[stable(feature = "extend_string", since = "1.4.0")]
1894 impl FromIterator<String> for String {
1895 fn from_iter<I: IntoIterator<Item = String>>(iter: I) -> String {
1896 let mut iterator = iter.into_iter();
1898 // Because we're iterating over `String`s, we can avoid at least
1899 // one allocation by getting the first string from the iterator
1900 // and appending to it all the subsequent strings.
1901 match iterator.next() {
1902 None => String::new(),
1904 buf.extend(iterator);
1911 #[cfg(not(no_global_oom_handling))]
1912 #[stable(feature = "box_str2", since = "1.45.0")]
1913 impl FromIterator<Box<str>> for String {
1914 fn from_iter<I: IntoIterator<Item = Box<str>>>(iter: I) -> String {
1915 let mut buf = String::new();
1921 #[cfg(not(no_global_oom_handling))]
1922 #[stable(feature = "herd_cows", since = "1.19.0")]
1923 impl<'a> FromIterator<Cow<'a, str>> for String {
1924 fn from_iter<I: IntoIterator<Item = Cow<'a, str>>>(iter: I) -> String {
1925 let mut iterator = iter.into_iter();
1927 // Because we're iterating over CoWs, we can (potentially) avoid at least
1928 // one allocation by getting the first item and appending to it all the
1929 // subsequent items.
1930 match iterator.next() {
1931 None => String::new(),
1933 let mut buf = cow.into_owned();
1934 buf.extend(iterator);
1941 #[cfg(not(no_global_oom_handling))]
1942 #[stable(feature = "rust1", since = "1.0.0")]
1943 impl Extend<char> for String {
1944 fn extend<I: IntoIterator<Item = char>>(&mut self, iter: I) {
1945 let iterator = iter.into_iter();
1946 let (lower_bound, _) = iterator.size_hint();
1947 self.reserve(lower_bound);
1948 iterator.for_each(move |c| self.push(c));
1952 fn extend_one(&mut self, c: char) {
1957 fn extend_reserve(&mut self, additional: usize) {
1958 self.reserve(additional);
1962 #[cfg(not(no_global_oom_handling))]
1963 #[stable(feature = "extend_ref", since = "1.2.0")]
1964 impl<'a> Extend<&'a char> for String {
1965 fn extend<I: IntoIterator<Item = &'a char>>(&mut self, iter: I) {
1966 self.extend(iter.into_iter().cloned());
1970 fn extend_one(&mut self, &c: &'a char) {
1975 fn extend_reserve(&mut self, additional: usize) {
1976 self.reserve(additional);
1980 #[cfg(not(no_global_oom_handling))]
1981 #[stable(feature = "rust1", since = "1.0.0")]
1982 impl<'a> Extend<&'a str> for String {
1983 fn extend<I: IntoIterator<Item = &'a str>>(&mut self, iter: I) {
1984 iter.into_iter().for_each(move |s| self.push_str(s));
1988 fn extend_one(&mut self, s: &'a str) {
1993 #[cfg(not(no_global_oom_handling))]
1994 #[stable(feature = "box_str2", since = "1.45.0")]
1995 impl Extend<Box<str>> for String {
1996 fn extend<I: IntoIterator<Item = Box<str>>>(&mut self, iter: I) {
1997 iter.into_iter().for_each(move |s| self.push_str(&s));
2001 #[cfg(not(no_global_oom_handling))]
2002 #[stable(feature = "extend_string", since = "1.4.0")]
2003 impl Extend<String> for String {
2004 fn extend<I: IntoIterator<Item = String>>(&mut self, iter: I) {
2005 iter.into_iter().for_each(move |s| self.push_str(&s));
2009 fn extend_one(&mut self, s: String) {
2014 #[cfg(not(no_global_oom_handling))]
2015 #[stable(feature = "herd_cows", since = "1.19.0")]
2016 impl<'a> Extend<Cow<'a, str>> for String {
2017 fn extend<I: IntoIterator<Item = Cow<'a, str>>>(&mut self, iter: I) {
2018 iter.into_iter().for_each(move |s| self.push_str(&s));
2022 fn extend_one(&mut self, s: Cow<'a, str>) {
2027 /// A convenience impl that delegates to the impl for `&str`.
2032 /// assert_eq!(String::from("Hello world").find("world"), Some(6));
2035 feature = "pattern",
2036 reason = "API not fully fleshed out and ready to be stabilized",
2039 impl<'a, 'b> Pattern<'a> for &'b String {
2040 type Searcher = <&'b str as Pattern<'a>>::Searcher;
2042 fn into_searcher(self, haystack: &'a str) -> <&'b str as Pattern<'a>>::Searcher {
2043 self[..].into_searcher(haystack)
2047 fn is_contained_in(self, haystack: &'a str) -> bool {
2048 self[..].is_contained_in(haystack)
2052 fn is_prefix_of(self, haystack: &'a str) -> bool {
2053 self[..].is_prefix_of(haystack)
2057 fn strip_prefix_of(self, haystack: &'a str) -> Option<&'a str> {
2058 self[..].strip_prefix_of(haystack)
2062 fn is_suffix_of(self, haystack: &'a str) -> bool {
2063 self[..].is_suffix_of(haystack)
2067 fn strip_suffix_of(self, haystack: &'a str) -> Option<&'a str> {
2068 self[..].strip_suffix_of(haystack)
2072 #[stable(feature = "rust1", since = "1.0.0")]
2073 impl PartialEq for String {
2075 fn eq(&self, other: &String) -> bool {
2076 PartialEq::eq(&self[..], &other[..])
2079 fn ne(&self, other: &String) -> bool {
2080 PartialEq::ne(&self[..], &other[..])
2084 macro_rules! impl_eq {
2085 ($lhs:ty, $rhs: ty) => {
2086 #[stable(feature = "rust1", since = "1.0.0")]
2087 #[allow(unused_lifetimes)]
2088 impl<'a, 'b> PartialEq<$rhs> for $lhs {
2090 fn eq(&self, other: &$rhs) -> bool {
2091 PartialEq::eq(&self[..], &other[..])
2094 fn ne(&self, other: &$rhs) -> bool {
2095 PartialEq::ne(&self[..], &other[..])
2099 #[stable(feature = "rust1", since = "1.0.0")]
2100 #[allow(unused_lifetimes)]
2101 impl<'a, 'b> PartialEq<$lhs> for $rhs {
2103 fn eq(&self, other: &$lhs) -> bool {
2104 PartialEq::eq(&self[..], &other[..])
2107 fn ne(&self, other: &$lhs) -> bool {
2108 PartialEq::ne(&self[..], &other[..])
2114 impl_eq! { String, str }
2115 impl_eq! { String, &'a str }
2116 #[cfg(not(no_global_oom_handling))]
2117 impl_eq! { Cow<'a, str>, str }
2118 #[cfg(not(no_global_oom_handling))]
2119 impl_eq! { Cow<'a, str>, &'b str }
2120 #[cfg(not(no_global_oom_handling))]
2121 impl_eq! { Cow<'a, str>, String }
2123 #[stable(feature = "rust1", since = "1.0.0")]
2124 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
2125 impl const Default for String {
2126 /// Creates an empty `String`.
2128 fn default() -> String {
2133 #[stable(feature = "rust1", since = "1.0.0")]
2134 impl fmt::Display for String {
2136 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2137 fmt::Display::fmt(&**self, f)
2141 #[stable(feature = "rust1", since = "1.0.0")]
2142 impl fmt::Debug for String {
2144 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2145 fmt::Debug::fmt(&**self, f)
2149 #[stable(feature = "rust1", since = "1.0.0")]
2150 impl hash::Hash for String {
2152 fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
2153 (**self).hash(hasher)
2157 /// Implements the `+` operator for concatenating two strings.
2159 /// This consumes the `String` on the left-hand side and re-uses its buffer (growing it if
2160 /// necessary). This is done to avoid allocating a new `String` and copying the entire contents on
2161 /// every operation, which would lead to *O*(*n*^2) running time when building an *n*-byte string by
2162 /// repeated concatenation.
2164 /// The string on the right-hand side is only borrowed; its contents are copied into the returned
2169 /// Concatenating two `String`s takes the first by value and borrows the second:
2172 /// let a = String::from("hello");
2173 /// let b = String::from(" world");
2175 /// // `a` is moved and can no longer be used here.
2178 /// If you want to keep using the first `String`, you can clone it and append to the clone instead:
2181 /// let a = String::from("hello");
2182 /// let b = String::from(" world");
2183 /// let c = a.clone() + &b;
2184 /// // `a` is still valid here.
2187 /// Concatenating `&str` slices can be done by converting the first to a `String`:
2190 /// let a = "hello";
2191 /// let b = " world";
2192 /// let c = a.to_string() + b;
2194 #[cfg(not(no_global_oom_handling))]
2195 #[stable(feature = "rust1", since = "1.0.0")]
2196 impl Add<&str> for String {
2197 type Output = String;
2200 fn add(mut self, other: &str) -> String {
2201 self.push_str(other);
2206 /// Implements the `+=` operator for appending to a `String`.
2208 /// This has the same behavior as the [`push_str`][String::push_str] method.
2209 #[cfg(not(no_global_oom_handling))]
2210 #[stable(feature = "stringaddassign", since = "1.12.0")]
2211 impl AddAssign<&str> for String {
2213 fn add_assign(&mut self, other: &str) {
2214 self.push_str(other);
2218 #[stable(feature = "rust1", since = "1.0.0")]
2219 impl ops::Index<ops::Range<usize>> for String {
2223 fn index(&self, index: ops::Range<usize>) -> &str {
2227 #[stable(feature = "rust1", since = "1.0.0")]
2228 impl ops::Index<ops::RangeTo<usize>> for String {
2232 fn index(&self, index: ops::RangeTo<usize>) -> &str {
2236 #[stable(feature = "rust1", since = "1.0.0")]
2237 impl ops::Index<ops::RangeFrom<usize>> for String {
2241 fn index(&self, index: ops::RangeFrom<usize>) -> &str {
2245 #[stable(feature = "rust1", since = "1.0.0")]
2246 impl ops::Index<ops::RangeFull> for String {
2250 fn index(&self, _index: ops::RangeFull) -> &str {
2251 unsafe { str::from_utf8_unchecked(&self.vec) }
2254 #[stable(feature = "inclusive_range", since = "1.26.0")]
2255 impl ops::Index<ops::RangeInclusive<usize>> for String {
2259 fn index(&self, index: ops::RangeInclusive<usize>) -> &str {
2260 Index::index(&**self, index)
2263 #[stable(feature = "inclusive_range", since = "1.26.0")]
2264 impl ops::Index<ops::RangeToInclusive<usize>> for String {
2268 fn index(&self, index: ops::RangeToInclusive<usize>) -> &str {
2269 Index::index(&**self, index)
2273 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2274 impl ops::IndexMut<ops::Range<usize>> for String {
2276 fn index_mut(&mut self, index: ops::Range<usize>) -> &mut str {
2277 &mut self[..][index]
2280 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2281 impl ops::IndexMut<ops::RangeTo<usize>> for String {
2283 fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut str {
2284 &mut self[..][index]
2287 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2288 impl ops::IndexMut<ops::RangeFrom<usize>> for String {
2290 fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut str {
2291 &mut self[..][index]
2294 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2295 impl ops::IndexMut<ops::RangeFull> for String {
2297 fn index_mut(&mut self, _index: ops::RangeFull) -> &mut str {
2298 unsafe { str::from_utf8_unchecked_mut(&mut *self.vec) }
2301 #[stable(feature = "inclusive_range", since = "1.26.0")]
2302 impl ops::IndexMut<ops::RangeInclusive<usize>> for String {
2304 fn index_mut(&mut self, index: ops::RangeInclusive<usize>) -> &mut str {
2305 IndexMut::index_mut(&mut **self, index)
2308 #[stable(feature = "inclusive_range", since = "1.26.0")]
2309 impl ops::IndexMut<ops::RangeToInclusive<usize>> for String {
2311 fn index_mut(&mut self, index: ops::RangeToInclusive<usize>) -> &mut str {
2312 IndexMut::index_mut(&mut **self, index)
2316 #[stable(feature = "rust1", since = "1.0.0")]
2317 impl ops::Deref for String {
2321 fn deref(&self) -> &str {
2322 unsafe { str::from_utf8_unchecked(&self.vec) }
2326 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2327 impl ops::DerefMut for String {
2329 fn deref_mut(&mut self) -> &mut str {
2330 unsafe { str::from_utf8_unchecked_mut(&mut *self.vec) }
2334 /// A type alias for [`Infallible`].
2336 /// This alias exists for backwards compatibility, and may be eventually deprecated.
2338 /// [`Infallible`]: core::convert::Infallible "convert::Infallible"
2339 #[stable(feature = "str_parse_error", since = "1.5.0")]
2340 pub type ParseError = core::convert::Infallible;
2342 #[cfg(not(no_global_oom_handling))]
2343 #[stable(feature = "rust1", since = "1.0.0")]
2344 impl FromStr for String {
2345 type Err = core::convert::Infallible;
2347 fn from_str(s: &str) -> Result<String, Self::Err> {
2352 /// A trait for converting a value to a `String`.
2354 /// This trait is automatically implemented for any type which implements the
2355 /// [`Display`] trait. As such, `ToString` shouldn't be implemented directly:
2356 /// [`Display`] should be implemented instead, and you get the `ToString`
2357 /// implementation for free.
2359 /// [`Display`]: fmt::Display
2360 #[cfg_attr(not(test), rustc_diagnostic_item = "ToString")]
2361 #[stable(feature = "rust1", since = "1.0.0")]
2362 pub trait ToString {
2363 /// Converts the given value to a `String`.
2371 /// let five = String::from("5");
2373 /// assert_eq!(five, i.to_string());
2375 #[rustc_conversion_suggestion]
2376 #[stable(feature = "rust1", since = "1.0.0")]
2377 fn to_string(&self) -> String;
2382 /// In this implementation, the `to_string` method panics
2383 /// if the `Display` implementation returns an error.
2384 /// This indicates an incorrect `Display` implementation
2385 /// since `fmt::Write for String` never returns an error itself.
2386 #[cfg(not(no_global_oom_handling))]
2387 #[stable(feature = "rust1", since = "1.0.0")]
2388 impl<T: fmt::Display + ?Sized> ToString for T {
2389 // A common guideline is to not inline generic functions. However,
2390 // removing `#[inline]` from this method causes non-negligible regressions.
2391 // See <https://github.com/rust-lang/rust/pull/74852>, the last attempt
2392 // to try to remove it.
2394 default fn to_string(&self) -> String {
2395 let mut buf = String::new();
2396 let mut formatter = core::fmt::Formatter::new(&mut buf);
2397 // Bypass format_args!() to avoid write_str with zero-length strs
2398 fmt::Display::fmt(self, &mut formatter)
2399 .expect("a Display implementation returned an error unexpectedly");
2404 #[cfg(not(no_global_oom_handling))]
2405 #[stable(feature = "char_to_string_specialization", since = "1.46.0")]
2406 impl ToString for char {
2408 fn to_string(&self) -> String {
2409 String::from(self.encode_utf8(&mut [0; 4]))
2413 #[cfg(not(no_global_oom_handling))]
2414 #[stable(feature = "u8_to_string_specialization", since = "1.54.0")]
2415 impl ToString for u8 {
2417 fn to_string(&self) -> String {
2418 let mut buf = String::with_capacity(3);
2422 buf.push((b'0' + n / 100) as char);
2425 buf.push((b'0' + n / 10) as char);
2428 buf.push((b'0' + n) as char);
2433 #[cfg(not(no_global_oom_handling))]
2434 #[stable(feature = "i8_to_string_specialization", since = "1.54.0")]
2435 impl ToString for i8 {
2437 fn to_string(&self) -> String {
2438 let mut buf = String::with_capacity(4);
2439 if self.is_negative() {
2442 let mut n = self.unsigned_abs();
2448 buf.push((b'0' + n / 10) as char);
2451 buf.push((b'0' + n) as char);
2456 #[cfg(not(no_global_oom_handling))]
2457 #[stable(feature = "str_to_string_specialization", since = "1.9.0")]
2458 impl ToString for str {
2460 fn to_string(&self) -> String {
2465 #[cfg(not(no_global_oom_handling))]
2466 #[stable(feature = "cow_str_to_string_specialization", since = "1.17.0")]
2467 impl ToString for Cow<'_, str> {
2469 fn to_string(&self) -> String {
2474 #[cfg(not(no_global_oom_handling))]
2475 #[stable(feature = "string_to_string_specialization", since = "1.17.0")]
2476 impl ToString for String {
2478 fn to_string(&self) -> String {
2483 #[stable(feature = "rust1", since = "1.0.0")]
2484 impl AsRef<str> for String {
2486 fn as_ref(&self) -> &str {
2491 #[stable(feature = "string_as_mut", since = "1.43.0")]
2492 impl AsMut<str> for String {
2494 fn as_mut(&mut self) -> &mut str {
2499 #[stable(feature = "rust1", since = "1.0.0")]
2500 impl AsRef<[u8]> for String {
2502 fn as_ref(&self) -> &[u8] {
2507 #[cfg(not(no_global_oom_handling))]
2508 #[stable(feature = "rust1", since = "1.0.0")]
2509 impl From<&str> for String {
2510 /// Converts a `&str` into a [`String`].
2512 /// The result is allocated on the heap.
2514 fn from(s: &str) -> String {
2519 #[cfg(not(no_global_oom_handling))]
2520 #[stable(feature = "from_mut_str_for_string", since = "1.44.0")]
2521 impl From<&mut str> for String {
2522 /// Converts a `&mut str` into a [`String`].
2524 /// The result is allocated on the heap.
2526 fn from(s: &mut str) -> String {
2531 #[cfg(not(no_global_oom_handling))]
2532 #[stable(feature = "from_ref_string", since = "1.35.0")]
2533 impl From<&String> for String {
2534 /// Converts a `&String` into a [`String`].
2536 /// This clones `s` and returns the clone.
2538 fn from(s: &String) -> String {
2543 // note: test pulls in libstd, which causes errors here
2545 #[stable(feature = "string_from_box", since = "1.18.0")]
2546 impl From<Box<str>> for String {
2547 /// Converts the given boxed `str` slice to a [`String`].
2548 /// It is notable that the `str` slice is owned.
2555 /// let s1: String = String::from("hello world");
2556 /// let s2: Box<str> = s1.into_boxed_str();
2557 /// let s3: String = String::from(s2);
2559 /// assert_eq!("hello world", s3)
2561 fn from(s: Box<str>) -> String {
2566 #[cfg(not(no_global_oom_handling))]
2567 #[stable(feature = "box_from_str", since = "1.20.0")]
2568 impl From<String> for Box<str> {
2569 /// Converts the given [`String`] to a boxed `str` slice that is owned.
2576 /// let s1: String = String::from("hello world");
2577 /// let s2: Box<str> = Box::from(s1);
2578 /// let s3: String = String::from(s2);
2580 /// assert_eq!("hello world", s3)
2582 fn from(s: String) -> Box<str> {
2587 #[cfg(not(no_global_oom_handling))]
2588 #[stable(feature = "string_from_cow_str", since = "1.14.0")]
2589 impl<'a> From<Cow<'a, str>> for String {
2590 /// Converts a clone-on-write string to an owned
2591 /// instance of [`String`].
2593 /// This extracts the owned string,
2594 /// clones the string if it is not already owned.
2599 /// # use std::borrow::Cow;
2600 /// // If the string is not owned...
2601 /// let cow: Cow<str> = Cow::Borrowed("eggplant");
2602 /// // It will allocate on the heap and copy the string.
2603 /// let owned: String = String::from(cow);
2604 /// assert_eq!(&owned[..], "eggplant");
2606 fn from(s: Cow<'a, str>) -> String {
2611 #[cfg(not(no_global_oom_handling))]
2612 #[stable(feature = "rust1", since = "1.0.0")]
2613 impl<'a> From<&'a str> for Cow<'a, str> {
2614 /// Converts a string slice into a [`Borrowed`] variant.
2615 /// No heap allocation is performed, and the string
2621 /// # use std::borrow::Cow;
2622 /// assert_eq!(Cow::from("eggplant"), Cow::Borrowed("eggplant"));
2625 /// [`Borrowed`]: crate::borrow::Cow::Borrowed "borrow::Cow::Borrowed"
2627 fn from(s: &'a str) -> Cow<'a, str> {
2632 #[cfg(not(no_global_oom_handling))]
2633 #[stable(feature = "rust1", since = "1.0.0")]
2634 impl<'a> From<String> for Cow<'a, str> {
2635 /// Converts a [`String`] into an [`Owned`] variant.
2636 /// No heap allocation is performed, and the string
2642 /// # use std::borrow::Cow;
2643 /// let s = "eggplant".to_string();
2644 /// let s2 = "eggplant".to_string();
2645 /// assert_eq!(Cow::from(s), Cow::<'static, str>::Owned(s2));
2648 /// [`Owned`]: crate::borrow::Cow::Owned "borrow::Cow::Owned"
2650 fn from(s: String) -> Cow<'a, str> {
2655 #[cfg(not(no_global_oom_handling))]
2656 #[stable(feature = "cow_from_string_ref", since = "1.28.0")]
2657 impl<'a> From<&'a String> for Cow<'a, str> {
2658 /// Converts a [`String`] reference into a [`Borrowed`] variant.
2659 /// No heap allocation is performed, and the string
2665 /// # use std::borrow::Cow;
2666 /// let s = "eggplant".to_string();
2667 /// assert_eq!(Cow::from(&s), Cow::Borrowed("eggplant"));
2670 /// [`Borrowed`]: crate::borrow::Cow::Borrowed "borrow::Cow::Borrowed"
2672 fn from(s: &'a String) -> Cow<'a, str> {
2673 Cow::Borrowed(s.as_str())
2677 #[cfg(not(no_global_oom_handling))]
2678 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2679 impl<'a> FromIterator<char> for Cow<'a, str> {
2680 fn from_iter<I: IntoIterator<Item = char>>(it: I) -> Cow<'a, str> {
2681 Cow::Owned(FromIterator::from_iter(it))
2685 #[cfg(not(no_global_oom_handling))]
2686 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2687 impl<'a, 'b> FromIterator<&'b str> for Cow<'a, str> {
2688 fn from_iter<I: IntoIterator<Item = &'b str>>(it: I) -> Cow<'a, str> {
2689 Cow::Owned(FromIterator::from_iter(it))
2693 #[cfg(not(no_global_oom_handling))]
2694 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2695 impl<'a> FromIterator<String> for Cow<'a, str> {
2696 fn from_iter<I: IntoIterator<Item = String>>(it: I) -> Cow<'a, str> {
2697 Cow::Owned(FromIterator::from_iter(it))
2701 #[stable(feature = "from_string_for_vec_u8", since = "1.14.0")]
2702 impl From<String> for Vec<u8> {
2703 /// Converts the given [`String`] to a vector [`Vec`] that holds values of type [`u8`].
2710 /// let s1 = String::from("hello world");
2711 /// let v1 = Vec::from(s1);
2714 /// println!("{}", b);
2717 fn from(string: String) -> Vec<u8> {
2722 #[cfg(not(no_global_oom_handling))]
2723 #[stable(feature = "rust1", since = "1.0.0")]
2724 impl fmt::Write for String {
2726 fn write_str(&mut self, s: &str) -> fmt::Result {
2732 fn write_char(&mut self, c: char) -> fmt::Result {
2738 /// A draining iterator for `String`.
2740 /// This struct is created by the [`drain`] method on [`String`]. See its
2741 /// documentation for more.
2743 /// [`drain`]: String::drain
2744 #[stable(feature = "drain", since = "1.6.0")]
2745 pub struct Drain<'a> {
2746 /// Will be used as &'a mut String in the destructor
2747 string: *mut String,
2748 /// Start of part to remove
2750 /// End of part to remove
2752 /// Current remaining range to remove
2756 #[stable(feature = "collection_debug", since = "1.17.0")]
2757 impl fmt::Debug for Drain<'_> {
2758 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2759 f.debug_tuple("Drain").field(&self.as_str()).finish()
2763 #[stable(feature = "drain", since = "1.6.0")]
2764 unsafe impl Sync for Drain<'_> {}
2765 #[stable(feature = "drain", since = "1.6.0")]
2766 unsafe impl Send for Drain<'_> {}
2768 #[stable(feature = "drain", since = "1.6.0")]
2769 impl Drop for Drain<'_> {
2770 fn drop(&mut self) {
2772 // Use Vec::drain. "Reaffirm" the bounds checks to avoid
2773 // panic code being inserted again.
2774 let self_vec = (*self.string).as_mut_vec();
2775 if self.start <= self.end && self.end <= self_vec.len() {
2776 self_vec.drain(self.start..self.end);
2782 impl<'a> Drain<'a> {
2783 /// Returns the remaining (sub)string of this iterator as a slice.
2788 /// let mut s = String::from("abc");
2789 /// let mut drain = s.drain(..);
2790 /// assert_eq!(drain.as_str(), "abc");
2791 /// let _ = drain.next().unwrap();
2792 /// assert_eq!(drain.as_str(), "bc");
2795 #[stable(feature = "string_drain_as_str", since = "1.55.0")]
2796 pub fn as_str(&self) -> &str {
2801 #[stable(feature = "string_drain_as_str", since = "1.55.0")]
2802 impl<'a> AsRef<str> for Drain<'a> {
2803 fn as_ref(&self) -> &str {
2808 #[stable(feature = "string_drain_as_str", since = "1.55.0")]
2809 impl<'a> AsRef<[u8]> for Drain<'a> {
2810 fn as_ref(&self) -> &[u8] {
2811 self.as_str().as_bytes()
2815 #[stable(feature = "drain", since = "1.6.0")]
2816 impl Iterator for Drain<'_> {
2820 fn next(&mut self) -> Option<char> {
2824 fn size_hint(&self) -> (usize, Option<usize>) {
2825 self.iter.size_hint()
2829 fn last(mut self) -> Option<char> {
2834 #[stable(feature = "drain", since = "1.6.0")]
2835 impl DoubleEndedIterator for Drain<'_> {
2837 fn next_back(&mut self) -> Option<char> {
2838 self.iter.next_back()
2842 #[stable(feature = "fused", since = "1.26.0")]
2843 impl FusedIterator for Drain<'_> {}
2845 #[cfg(not(no_global_oom_handling))]
2846 #[stable(feature = "from_char_for_string", since = "1.46.0")]
2847 impl From<char> for String {
2848 /// Allocates an owned [`String`] from a single character.
2852 /// let c: char = 'a';
2853 /// let s: String = String::from(c);
2854 /// assert_eq!("a", &s[..]);
2857 fn from(c: char) -> Self {