1 //! A UTF-8 encoded, growable string.
3 //! This module contains the [`String`] type, a trait for converting
4 //! [`ToString`]s, and several error types that may result from working with
7 //! [`ToString`]: trait.ToString.html
11 //! There are multiple ways to create a new [`String`] from a string literal:
14 //! let s = "Hello".to_string();
16 //! let s = String::from("world");
17 //! let s: String = "also this".into();
20 //! You can create a new [`String`] from an existing one by concatenating with
23 //! [`String`]: struct.String.html
26 //! let s = "Hello".to_string();
28 //! let message = s + " world!";
31 //! If you have a vector of valid UTF-8 bytes, you can make a [`String`] out of
32 //! it. You can do the reverse too.
35 //! let sparkle_heart = vec![240, 159, 146, 150];
37 //! // We know these bytes are valid, so we'll use `unwrap()`.
38 //! let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
40 //! assert_eq!("๐", sparkle_heart);
42 //! let bytes = sparkle_heart.into_bytes();
44 //! assert_eq!(bytes, [240, 159, 146, 150]);
47 #![stable(feature = "rust1", since = "1.0.0")]
49 use core::char::{decode_utf16, REPLACEMENT_CHARACTER};
52 use core::iter::{FromIterator, FusedIterator};
53 use core::ops::{self, Add, AddAssign, Index, IndexMut, RangeBounds};
54 use core::ops::Bound::{Excluded, Included, Unbounded};
56 use core::str::{pattern::Pattern, lossy};
58 use crate::borrow::{Cow, ToOwned};
59 use crate::collections::TryReserveError;
60 use crate::boxed::Box;
61 use crate::str::{self, from_boxed_utf8_unchecked, FromStr, Utf8Error, Chars};
64 /// A UTF-8 encoded, growable string.
66 /// The `String` type is the most common string type that has ownership over the
67 /// contents of the string. It has a close relationship with its borrowed
68 /// counterpart, the primitive [`str`].
70 /// [`str`]: ../../std/primitive.str.html
74 /// You can create a `String` from a literal string with [`String::from`]:
77 /// let hello = String::from("Hello, world!");
80 /// You can append a [`char`] to a `String` with the [`push`] method, and
81 /// append a [`&str`] with the [`push_str`] method:
84 /// let mut hello = String::from("Hello, ");
87 /// hello.push_str("orld!");
90 /// [`String::from`]: #method.from
91 /// [`char`]: ../../std/primitive.char.html
92 /// [`push`]: #method.push
93 /// [`push_str`]: #method.push_str
95 /// If you have a vector of UTF-8 bytes, you can create a `String` from it with
96 /// the [`from_utf8`] method:
99 /// // some bytes, in a vector
100 /// let sparkle_heart = vec![240, 159, 146, 150];
102 /// // We know these bytes are valid, so we'll use `unwrap()`.
103 /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
105 /// assert_eq!("๐", sparkle_heart);
108 /// [`from_utf8`]: #method.from_utf8
112 /// `String`s are always valid UTF-8. This has a few implications, the first of
113 /// which is that if you need a non-UTF-8 string, consider [`OsString`]. It is
114 /// similar, but without the UTF-8 constraint. The second implication is that
115 /// you cannot index into a `String`:
117 /// ```compile_fail,E0277
120 /// println!("The first letter of s is {}", s[0]); // ERROR!!!
123 /// [`OsString`]: ../../std/ffi/struct.OsString.html
125 /// Indexing is intended to be a constant-time operation, but UTF-8 encoding
126 /// does not allow us to do this. Furthermore, it's not clear what sort of
127 /// thing the index should return: a byte, a codepoint, or a grapheme cluster.
128 /// The [`bytes`] and [`chars`] methods return iterators over the first
129 /// two, respectively.
131 /// [`bytes`]: #method.bytes
132 /// [`chars`]: #method.chars
136 /// `String`s implement [`Deref`]`<Target=str>`, and so inherit all of [`str`]'s
137 /// methods. In addition, this means that you can pass a `String` to a
138 /// function which takes a [`&str`] by using an ampersand (`&`):
141 /// fn takes_str(s: &str) { }
143 /// let s = String::from("Hello");
148 /// This will create a [`&str`] from the `String` and pass it in. This
149 /// conversion is very inexpensive, and so generally, functions will accept
150 /// [`&str`]s as arguments unless they need a `String` for some specific
153 /// In certain cases Rust doesn't have enough information to make this
154 /// conversion, known as [`Deref`] coercion. In the following example a string
155 /// slice [`&'a str`][`&str`] implements the trait `TraitExample`, and the function
156 /// `example_func` takes anything that implements the trait. In this case Rust
157 /// would need to make two implicit conversions, which Rust doesn't have the
158 /// means to do. For that reason, the following example will not compile.
160 /// ```compile_fail,E0277
161 /// trait TraitExample {}
163 /// impl<'a> TraitExample for &'a str {}
165 /// fn example_func<A: TraitExample>(example_arg: A) {}
167 /// let example_string = String::from("example_string");
168 /// example_func(&example_string);
171 /// There are two options that would work instead. The first would be to
172 /// change the line `example_func(&example_string);` to
173 /// `example_func(example_string.as_str());`, using the method [`as_str()`]
174 /// to explicitly extract the string slice containing the string. The second
175 /// way changes `example_func(&example_string);` to
176 /// `example_func(&*example_string);`. In this case we are dereferencing a
177 /// `String` to a [`str`][`&str`], then referencing the [`str`][`&str`] back to
178 /// [`&str`]. The second way is more idiomatic, however both work to do the
179 /// conversion explicitly rather than relying on the implicit conversion.
183 /// A `String` is made up of three components: a pointer to some bytes, a
184 /// length, and a capacity. The pointer points to an internal buffer `String`
185 /// uses to store its data. The length is the number of bytes currently stored
186 /// in the buffer, and the capacity is the size of the buffer in bytes. As such,
187 /// the length will always be less than or equal to the capacity.
189 /// This buffer is always stored on the heap.
191 /// You can look at these with the [`as_ptr`], [`len`], and [`capacity`]
197 /// let story = String::from("Once upon a time...");
199 // FIXME Update this when vec_into_raw_parts is stabilized
200 /// // Prevent automatically dropping the String's data
201 /// let mut story = mem::ManuallyDrop::new(story);
203 /// let ptr = story.as_mut_ptr();
204 /// let len = story.len();
205 /// let capacity = story.capacity();
207 /// // story has nineteen bytes
208 /// assert_eq!(19, len);
210 /// // We can re-build a String out of ptr, len, and capacity. This is all
211 /// // unsafe because we are responsible for making sure the components are
213 /// let s = unsafe { String::from_raw_parts(ptr, len, capacity) } ;
215 /// assert_eq!(String::from("Once upon a time..."), s);
218 /// [`as_ptr`]: #method.as_ptr
219 /// [`len`]: #method.len
220 /// [`capacity`]: #method.capacity
222 /// If a `String` has enough capacity, adding elements to it will not
223 /// re-allocate. For example, consider this program:
226 /// let mut s = String::new();
228 /// println!("{}", s.capacity());
231 /// s.push_str("hello");
232 /// println!("{}", s.capacity());
236 /// This will output the following:
247 /// At first, we have no memory allocated at all, but as we append to the
248 /// string, it increases its capacity appropriately. If we instead use the
249 /// [`with_capacity`] method to allocate the correct capacity initially:
252 /// let mut s = String::with_capacity(25);
254 /// println!("{}", s.capacity());
257 /// s.push_str("hello");
258 /// println!("{}", s.capacity());
262 /// [`with_capacity`]: #method.with_capacity
264 /// We end up with a different output:
275 /// Here, there's no need to allocate more memory inside the loop.
277 /// [`&str`]: ../../std/primitive.str.html
278 /// [`Deref`]: ../../std/ops/trait.Deref.html
279 /// [`as_str()`]: struct.String.html#method.as_str
280 #[derive(PartialOrd, Eq, Ord)]
281 #[stable(feature = "rust1", since = "1.0.0")]
286 /// A possible error value when converting a `String` from a UTF-8 byte vector.
288 /// This type is the error type for the [`from_utf8`] method on [`String`]. It
289 /// is designed in such a way to carefully avoid reallocations: the
290 /// [`into_bytes`] method will give back the byte vector that was used in the
291 /// conversion attempt.
293 /// [`from_utf8`]: struct.String.html#method.from_utf8
294 /// [`String`]: struct.String.html
295 /// [`into_bytes`]: struct.FromUtf8Error.html#method.into_bytes
297 /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
298 /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
299 /// an analogue to `FromUtf8Error`, and you can get one from a `FromUtf8Error`
300 /// through the [`utf8_error`] method.
302 /// [`Utf8Error`]: ../../std/str/struct.Utf8Error.html
303 /// [`std::str`]: ../../std/str/index.html
304 /// [`u8`]: ../../std/primitive.u8.html
305 /// [`&str`]: ../../std/primitive.str.html
306 /// [`utf8_error`]: #method.utf8_error
313 /// // some invalid bytes, in a vector
314 /// let bytes = vec![0, 159];
316 /// let value = String::from_utf8(bytes);
318 /// assert!(value.is_err());
319 /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
321 #[stable(feature = "rust1", since = "1.0.0")]
323 pub struct FromUtf8Error {
328 /// A possible error value when converting a `String` from a UTF-16 byte slice.
330 /// This type is the error type for the [`from_utf16`] method on [`String`].
332 /// [`from_utf16`]: struct.String.html#method.from_utf16
333 /// [`String`]: struct.String.html
340 /// // ๐mu<invalid>ic
341 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
342 /// 0xD800, 0x0069, 0x0063];
344 /// assert!(String::from_utf16(v).is_err());
346 #[stable(feature = "rust1", since = "1.0.0")]
348 pub struct FromUtf16Error(());
351 /// Creates a new empty `String`.
353 /// Given that the `String` is empty, this will not allocate any initial
354 /// buffer. While that means that this initial operation is very
355 /// inexpensive, it may cause excessive allocation later when you add
356 /// data. If you have an idea of how much data the `String` will hold,
357 /// consider the [`with_capacity`] method to prevent excessive
360 /// [`with_capacity`]: #method.with_capacity
367 /// let s = String::new();
370 #[stable(feature = "rust1", since = "1.0.0")]
371 pub const fn new() -> String {
372 String { vec: Vec::new() }
375 /// Creates a new empty `String` with a particular capacity.
377 /// `String`s have an internal buffer to hold their data. The capacity is
378 /// the length of that buffer, and can be queried with the [`capacity`]
379 /// method. This method creates an empty `String`, but one with an initial
380 /// buffer that can hold `capacity` bytes. This is useful when you may be
381 /// appending a bunch of data to the `String`, reducing the number of
382 /// reallocations it needs to do.
384 /// [`capacity`]: #method.capacity
386 /// If the given capacity is `0`, no allocation will occur, and this method
387 /// is identical to the [`new`] method.
389 /// [`new`]: #method.new
396 /// let mut s = String::with_capacity(10);
398 /// // The String contains no chars, even though it has capacity for more
399 /// assert_eq!(s.len(), 0);
401 /// // These are all done without reallocating...
402 /// let cap = s.capacity();
407 /// assert_eq!(s.capacity(), cap);
409 /// // ...but this may make the vector reallocate
413 #[stable(feature = "rust1", since = "1.0.0")]
414 pub fn with_capacity(capacity: usize) -> String {
415 String { vec: Vec::with_capacity(capacity) }
418 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
419 // required for this method definition, is not available. Since we don't
420 // require this method for testing purposes, I'll just stub it
421 // NB see the slice::hack module in slice.rs for more information
424 pub fn from_str(_: &str) -> String {
425 panic!("not available with cfg(test)");
428 /// Converts a vector of bytes to a `String`.
430 /// A string ([`String`]) is made of bytes ([`u8`]), and a vector of bytes
431 /// ([`Vec<u8>`]) is made of bytes, so this function converts between the
432 /// two. Not all byte slices are valid `String`s, however: `String`
433 /// requires that it is valid UTF-8. `from_utf8()` checks to ensure that
434 /// the bytes are valid UTF-8, and then does the conversion.
436 /// If you are sure that the byte slice is valid UTF-8, and you don't want
437 /// to incur the overhead of the validity check, there is an unsafe version
438 /// of this function, [`from_utf8_unchecked`], which has the same behavior
439 /// but skips the check.
441 /// This method will take care to not copy the vector, for efficiency's
444 /// If you need a [`&str`] instead of a `String`, consider
445 /// [`str::from_utf8`].
447 /// The inverse of this method is [`into_bytes`].
451 /// Returns [`Err`] if the slice is not UTF-8 with a description as to why the
452 /// provided bytes are not UTF-8. The vector you moved in is also included.
459 /// // some bytes, in a vector
460 /// let sparkle_heart = vec![240, 159, 146, 150];
462 /// // We know these bytes are valid, so we'll use `unwrap()`.
463 /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
465 /// assert_eq!("๐", sparkle_heart);
471 /// // some invalid bytes, in a vector
472 /// let sparkle_heart = vec![0, 159, 146, 150];
474 /// assert!(String::from_utf8(sparkle_heart).is_err());
477 /// See the docs for [`FromUtf8Error`] for more details on what you can do
480 /// [`from_utf8_unchecked`]: struct.String.html#method.from_utf8_unchecked
481 /// [`String`]: struct.String.html
482 /// [`u8`]: ../../std/primitive.u8.html
483 /// [`Vec<u8>`]: ../../std/vec/struct.Vec.html
484 /// [`str::from_utf8`]: ../../std/str/fn.from_utf8.html
485 /// [`into_bytes`]: struct.String.html#method.into_bytes
486 /// [`FromUtf8Error`]: struct.FromUtf8Error.html
487 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
489 #[stable(feature = "rust1", since = "1.0.0")]
490 pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error> {
491 match str::from_utf8(&vec) {
492 Ok(..) => Ok(String { vec }),
502 /// Converts a slice of bytes to a string, including invalid characters.
504 /// Strings are made of bytes ([`u8`]), and a slice of bytes
505 /// ([`&[u8]`][byteslice]) is made of bytes, so this function converts
506 /// between the two. Not all byte slices are valid strings, however: strings
507 /// are required to be valid UTF-8. During this conversion,
508 /// `from_utf8_lossy()` will replace any invalid UTF-8 sequences with
509 /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD], which looks like this: ๏ฟฝ
511 /// [`u8`]: ../../std/primitive.u8.html
512 /// [byteslice]: ../../std/primitive.slice.html
513 /// [U+FFFD]: ../char/constant.REPLACEMENT_CHARACTER.html
515 /// If you are sure that the byte slice is valid UTF-8, and you don't want
516 /// to incur the overhead of the conversion, there is an unsafe version
517 /// of this function, [`from_utf8_unchecked`], which has the same behavior
518 /// but skips the checks.
520 /// [`from_utf8_unchecked`]: struct.String.html#method.from_utf8_unchecked
522 /// This function returns a [`Cow<'a, str>`]. If our byte slice is invalid
523 /// UTF-8, then we need to insert the replacement characters, which will
524 /// change the size of the string, and hence, require a `String`. But if
525 /// it's already valid UTF-8, we don't need a new allocation. This return
526 /// type allows us to handle both cases.
528 /// [`Cow<'a, str>`]: ../../std/borrow/enum.Cow.html
535 /// // some bytes, in a vector
536 /// let sparkle_heart = vec![240, 159, 146, 150];
538 /// let sparkle_heart = String::from_utf8_lossy(&sparkle_heart);
540 /// assert_eq!("๐", sparkle_heart);
546 /// // some invalid bytes
547 /// let input = b"Hello \xF0\x90\x80World";
548 /// let output = String::from_utf8_lossy(input);
550 /// assert_eq!("Hello ๏ฟฝWorld", output);
552 #[stable(feature = "rust1", since = "1.0.0")]
553 pub fn from_utf8_lossy(v: &[u8]) -> Cow<'_, str> {
554 let mut iter = lossy::Utf8Lossy::from_bytes(v).chunks();
556 let (first_valid, first_broken) = if let Some(chunk) = iter.next() {
557 let lossy::Utf8LossyChunk { valid, broken } = chunk;
558 if valid.len() == v.len() {
559 debug_assert!(broken.is_empty());
560 return Cow::Borrowed(valid);
564 return Cow::Borrowed("");
567 const REPLACEMENT: &str = "\u{FFFD}";
569 let mut res = String::with_capacity(v.len());
570 res.push_str(first_valid);
571 if !first_broken.is_empty() {
572 res.push_str(REPLACEMENT);
575 for lossy::Utf8LossyChunk { valid, broken } in iter {
577 if !broken.is_empty() {
578 res.push_str(REPLACEMENT);
585 /// Decode a UTF-16 encoded vector `v` into a `String`, returning [`Err`]
586 /// if `v` contains any invalid data.
588 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
596 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
597 /// 0x0073, 0x0069, 0x0063];
598 /// assert_eq!(String::from("๐music"),
599 /// String::from_utf16(v).unwrap());
601 /// // ๐mu<invalid>ic
602 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
603 /// 0xD800, 0x0069, 0x0063];
604 /// assert!(String::from_utf16(v).is_err());
606 #[stable(feature = "rust1", since = "1.0.0")]
607 pub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error> {
608 // This isn't done via collect::<Result<_, _>>() for performance reasons.
609 // FIXME: the function can be simplified again when #48994 is closed.
610 let mut ret = String::with_capacity(v.len());
611 for c in decode_utf16(v.iter().cloned()) {
615 return Err(FromUtf16Error(()));
621 /// Decode a UTF-16 encoded slice `v` into a `String`, replacing
622 /// invalid data with [the replacement character (`U+FFFD`)][U+FFFD].
624 /// Unlike [`from_utf8_lossy`] which returns a [`Cow<'a, str>`],
625 /// `from_utf16_lossy` returns a `String` since the UTF-16 to UTF-8
626 /// conversion requires a memory allocation.
628 /// [`from_utf8_lossy`]: #method.from_utf8_lossy
629 /// [`Cow<'a, str>`]: ../borrow/enum.Cow.html
630 /// [U+FFFD]: ../char/constant.REPLACEMENT_CHARACTER.html
637 /// // ๐mus<invalid>ic<invalid>
638 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
639 /// 0x0073, 0xDD1E, 0x0069, 0x0063,
642 /// assert_eq!(String::from("๐mus\u{FFFD}ic\u{FFFD}"),
643 /// String::from_utf16_lossy(v));
646 #[stable(feature = "rust1", since = "1.0.0")]
647 pub fn from_utf16_lossy(v: &[u16]) -> String {
648 decode_utf16(v.iter().cloned()).map(|r| r.unwrap_or(REPLACEMENT_CHARACTER)).collect()
651 /// Decomposes a `String` into its raw components.
653 /// Returns the raw pointer to the underlying data, the length of
654 /// the string (in bytes), and the allocated capacity of the data
655 /// (in bytes). These are the same arguments in the same order as
656 /// the arguments to [`from_raw_parts`].
658 /// After calling this function, the caller is responsible for the
659 /// memory previously managed by the `String`. The only way to do
660 /// this is to convert the raw pointer, length, and capacity back
661 /// into a `String` with the [`from_raw_parts`] function, allowing
662 /// the destructor to perform the cleanup.
664 /// [`from_raw_parts`]: #method.from_raw_parts
669 /// #![feature(vec_into_raw_parts)]
670 /// let s = String::from("hello");
672 /// let (ptr, len, cap) = s.into_raw_parts();
674 /// let rebuilt = unsafe { String::from_raw_parts(ptr, len, cap) };
675 /// assert_eq!(rebuilt, "hello");
677 #[unstable(feature = "vec_into_raw_parts", reason = "new API", issue = "65816")]
678 pub fn into_raw_parts(self) -> (*mut u8, usize, usize) {
679 self.vec.into_raw_parts()
682 /// Creates a new `String` from a length, capacity, and pointer.
686 /// This is highly unsafe, due to the number of invariants that aren't
689 /// * The memory at `ptr` needs to have been previously allocated by the
690 /// same allocator the standard library uses, with a required alignment of exactly 1.
691 /// * `length` needs to be less than or equal to `capacity`.
692 /// * `capacity` needs to be the correct value.
694 /// Violating these may cause problems like corrupting the allocator's
695 /// internal data structures.
697 /// The ownership of `ptr` is effectively transferred to the
698 /// `String` which may then deallocate, reallocate or change the
699 /// contents of memory pointed to by the pointer at will. Ensure
700 /// that nothing else uses the pointer after calling this
711 /// let s = String::from("hello");
713 // FIXME Update this when vec_into_raw_parts is stabilized
714 /// // Prevent automatically dropping the String's data
715 /// let mut s = mem::ManuallyDrop::new(s);
717 /// let ptr = s.as_mut_ptr();
718 /// let len = s.len();
719 /// let capacity = s.capacity();
721 /// let s = String::from_raw_parts(ptr, len, capacity);
723 /// assert_eq!(String::from("hello"), s);
727 #[stable(feature = "rust1", since = "1.0.0")]
728 pub unsafe fn from_raw_parts(buf: *mut u8, length: usize, capacity: usize) -> String {
729 String { vec: Vec::from_raw_parts(buf, length, capacity) }
732 /// Converts a vector of bytes to a `String` without checking that the
733 /// string contains valid UTF-8.
735 /// See the safe version, [`from_utf8`], for more details.
737 /// [`from_utf8`]: struct.String.html#method.from_utf8
741 /// This function is unsafe because it does not check that the bytes passed
742 /// to it are valid UTF-8. If this constraint is violated, it may cause
743 /// memory unsafety issues with future users of the `String`, as the rest of
744 /// the standard library assumes that `String`s are valid UTF-8.
751 /// // some bytes, in a vector
752 /// let sparkle_heart = vec![240, 159, 146, 150];
754 /// let sparkle_heart = unsafe {
755 /// String::from_utf8_unchecked(sparkle_heart)
758 /// assert_eq!("๐", sparkle_heart);
761 #[stable(feature = "rust1", since = "1.0.0")]
762 pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String {
763 String { vec: bytes }
766 /// Converts a `String` into a byte vector.
768 /// This consumes the `String`, so we do not need to copy its contents.
775 /// let s = String::from("hello");
776 /// let bytes = s.into_bytes();
778 /// assert_eq!(&[104, 101, 108, 108, 111][..], &bytes[..]);
781 #[stable(feature = "rust1", since = "1.0.0")]
782 pub fn into_bytes(self) -> Vec<u8> {
786 /// Extracts a string slice containing the entire `String`.
793 /// let s = String::from("foo");
795 /// assert_eq!("foo", s.as_str());
798 #[stable(feature = "string_as_str", since = "1.7.0")]
799 pub fn as_str(&self) -> &str {
803 /// Converts a `String` into a mutable string slice.
810 /// let mut s = String::from("foobar");
811 /// let s_mut_str = s.as_mut_str();
813 /// s_mut_str.make_ascii_uppercase();
815 /// assert_eq!("FOOBAR", s_mut_str);
818 #[stable(feature = "string_as_str", since = "1.7.0")]
819 pub fn as_mut_str(&mut self) -> &mut str {
823 /// Appends a given string slice onto the end of this `String`.
830 /// let mut s = String::from("foo");
832 /// s.push_str("bar");
834 /// assert_eq!("foobar", s);
837 #[stable(feature = "rust1", since = "1.0.0")]
838 pub fn push_str(&mut self, string: &str) {
839 self.vec.extend_from_slice(string.as_bytes())
842 /// Returns this `String`'s capacity, in bytes.
849 /// let s = String::with_capacity(10);
851 /// assert!(s.capacity() >= 10);
854 #[stable(feature = "rust1", since = "1.0.0")]
855 pub fn capacity(&self) -> usize {
859 /// Ensures that this `String`'s capacity is at least `additional` bytes
860 /// larger than its length.
862 /// The capacity may be increased by more than `additional` bytes if it
863 /// chooses, to prevent frequent reallocations.
865 /// If you do not want this "at least" behavior, see the [`reserve_exact`]
870 /// Panics if the new capacity overflows [`usize`].
872 /// [`reserve_exact`]: struct.String.html#method.reserve_exact
873 /// [`usize`]: ../../std/primitive.usize.html
880 /// let mut s = String::new();
884 /// assert!(s.capacity() >= 10);
887 /// This may not actually increase the capacity:
890 /// let mut s = String::with_capacity(10);
894 /// // s now has a length of 2 and a capacity of 10
895 /// assert_eq!(2, s.len());
896 /// assert_eq!(10, s.capacity());
898 /// // Since we already have an extra 8 capacity, calling this...
901 /// // ... doesn't actually increase.
902 /// assert_eq!(10, s.capacity());
905 #[stable(feature = "rust1", since = "1.0.0")]
906 pub fn reserve(&mut self, additional: usize) {
907 self.vec.reserve(additional)
910 /// Ensures that this `String`'s capacity is `additional` bytes
911 /// larger than its length.
913 /// Consider using the [`reserve`] method unless you absolutely know
914 /// better than the allocator.
916 /// [`reserve`]: #method.reserve
920 /// Panics if the new capacity overflows `usize`.
927 /// let mut s = String::new();
929 /// s.reserve_exact(10);
931 /// assert!(s.capacity() >= 10);
934 /// This may 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...
946 /// s.reserve_exact(8);
948 /// // ... doesn't actually increase.
949 /// assert_eq!(10, s.capacity());
952 #[stable(feature = "rust1", since = "1.0.0")]
953 pub fn reserve_exact(&mut self, additional: usize) {
954 self.vec.reserve_exact(additional)
957 /// Tries to reserve capacity for at least `additional` more elements to be inserted
958 /// in the given `String`. The collection may reserve more space to avoid
959 /// frequent reallocations. After calling `reserve`, capacity will be
960 /// greater than or equal to `self.len() + additional`. Does nothing if
961 /// capacity is already sufficient.
965 /// If the capacity overflows, or the allocator reports a failure, then an error
971 /// #![feature(try_reserve)]
972 /// use std::collections::TryReserveError;
974 /// fn process_data(data: &str) -> Result<String, TryReserveError> {
975 /// let mut output = String::new();
977 /// // Pre-reserve the memory, exiting if we can't
978 /// output.try_reserve(data.len())?;
980 /// // Now we know this can't OOM in the middle of our complex work
981 /// output.push_str(data);
985 /// # process_data("rust").expect("why is the test harness OOMing on 4 bytes?");
987 #[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
988 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
989 self.vec.try_reserve(additional)
992 /// Tries to reserves the minimum capacity for exactly `additional` more elements to
993 /// be inserted in the given `String`. After calling `reserve_exact`,
994 /// capacity will be greater than or equal to `self.len() + additional`.
995 /// Does nothing if the capacity is already sufficient.
997 /// Note that the allocator may give the collection more space than it
998 /// requests. Therefore, capacity can not be relied upon to be precisely
999 /// minimal. Prefer `reserve` if future insertions are expected.
1003 /// If the capacity overflows, or the allocator reports a failure, then an error
1009 /// #![feature(try_reserve)]
1010 /// use std::collections::TryReserveError;
1012 /// fn process_data(data: &str) -> Result<String, TryReserveError> {
1013 /// let mut output = String::new();
1015 /// // Pre-reserve the memory, exiting if we can't
1016 /// output.try_reserve(data.len())?;
1018 /// // Now we know this can't OOM in the middle of our complex work
1019 /// output.push_str(data);
1023 /// # process_data("rust").expect("why is the test harness OOMing on 4 bytes?");
1025 #[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
1026 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
1027 self.vec.try_reserve_exact(additional)
1030 /// Shrinks the capacity of this `String` to match its length.
1037 /// let mut s = String::from("foo");
1040 /// assert!(s.capacity() >= 100);
1042 /// s.shrink_to_fit();
1043 /// assert_eq!(3, s.capacity());
1046 #[stable(feature = "rust1", since = "1.0.0")]
1047 pub fn shrink_to_fit(&mut self) {
1048 self.vec.shrink_to_fit()
1051 /// Shrinks the capacity of this `String` with a lower bound.
1053 /// The capacity will remain at least as large as both the length
1054 /// and the supplied value.
1056 /// Panics if the current capacity is smaller than the supplied
1057 /// minimum capacity.
1062 /// #![feature(shrink_to)]
1063 /// let mut s = String::from("foo");
1066 /// assert!(s.capacity() >= 100);
1068 /// s.shrink_to(10);
1069 /// assert!(s.capacity() >= 10);
1071 /// assert!(s.capacity() >= 3);
1074 #[unstable(feature = "shrink_to", reason = "new API", issue="56431")]
1075 pub fn shrink_to(&mut self, min_capacity: usize) {
1076 self.vec.shrink_to(min_capacity)
1079 /// Appends the given [`char`] to the end of this `String`.
1081 /// [`char`]: ../../std/primitive.char.html
1088 /// let mut s = String::from("abc");
1094 /// assert_eq!("abc123", s);
1097 #[stable(feature = "rust1", since = "1.0.0")]
1098 pub fn push(&mut self, ch: char) {
1099 match ch.len_utf8() {
1100 1 => self.vec.push(ch as u8),
1101 _ => self.vec.extend_from_slice(ch.encode_utf8(&mut [0; 4]).as_bytes()),
1105 /// Returns a byte slice of this `String`'s contents.
1107 /// The inverse of this method is [`from_utf8`].
1109 /// [`from_utf8`]: #method.from_utf8
1116 /// let s = String::from("hello");
1118 /// assert_eq!(&[104, 101, 108, 108, 111], s.as_bytes());
1121 #[stable(feature = "rust1", since = "1.0.0")]
1122 pub fn as_bytes(&self) -> &[u8] {
1126 /// Shortens this `String` to the specified length.
1128 /// If `new_len` is greater than the string's current length, this has no
1131 /// Note that this method has no effect on the allocated capacity
1136 /// Panics if `new_len` does not lie on a [`char`] boundary.
1138 /// [`char`]: ../../std/primitive.char.html
1145 /// let mut s = String::from("hello");
1149 /// assert_eq!("he", s);
1152 #[stable(feature = "rust1", since = "1.0.0")]
1153 pub fn truncate(&mut self, new_len: usize) {
1154 if new_len <= self.len() {
1155 assert!(self.is_char_boundary(new_len));
1156 self.vec.truncate(new_len)
1160 /// Removes the last character from the string buffer and returns it.
1162 /// Returns [`None`] if this `String` is empty.
1164 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1171 /// let mut s = String::from("foo");
1173 /// assert_eq!(s.pop(), Some('o'));
1174 /// assert_eq!(s.pop(), Some('o'));
1175 /// assert_eq!(s.pop(), Some('f'));
1177 /// assert_eq!(s.pop(), None);
1180 #[stable(feature = "rust1", since = "1.0.0")]
1181 pub fn pop(&mut self) -> Option<char> {
1182 let ch = self.chars().rev().next()?;
1183 let newlen = self.len() - ch.len_utf8();
1185 self.vec.set_len(newlen);
1190 /// Removes a [`char`] from this `String` at a byte position and returns it.
1192 /// This is an `O(n)` operation, as it requires copying every element in the
1197 /// Panics if `idx` is larger than or equal to the `String`'s length,
1198 /// or if it does not lie on a [`char`] boundary.
1200 /// [`char`]: ../../std/primitive.char.html
1207 /// let mut s = String::from("foo");
1209 /// assert_eq!(s.remove(0), 'f');
1210 /// assert_eq!(s.remove(1), 'o');
1211 /// assert_eq!(s.remove(0), 'o');
1214 #[stable(feature = "rust1", since = "1.0.0")]
1215 pub fn remove(&mut self, idx: usize) -> char {
1216 let ch = match self[idx..].chars().next() {
1218 None => panic!("cannot remove a char from the end of a string"),
1221 let next = idx + ch.len_utf8();
1222 let len = self.len();
1224 ptr::copy(self.vec.as_ptr().add(next),
1225 self.vec.as_mut_ptr().add(idx),
1227 self.vec.set_len(len - (next - idx));
1232 /// Retains only the characters specified by the predicate.
1234 /// In other words, remove all characters `c` such that `f(c)` returns `false`.
1235 /// This method operates in place, visiting each character exactly once in the
1236 /// original order, and preserves the order of the retained characters.
1241 /// let mut s = String::from("f_o_ob_ar");
1243 /// s.retain(|c| c != '_');
1245 /// assert_eq!(s, "foobar");
1248 /// The exact order may be useful for tracking external state, like an index.
1251 /// let mut s = String::from("abcde");
1252 /// let keep = [false, true, true, false, true];
1254 /// s.retain(|_| (keep[i], i += 1).0);
1255 /// assert_eq!(s, "bce");
1258 #[stable(feature = "string_retain", since = "1.26.0")]
1259 pub fn retain<F>(&mut self, mut f: F)
1260 where F: FnMut(char) -> bool
1262 let len = self.len();
1263 let mut del_bytes = 0;
1268 self.get_unchecked(idx..len).chars().next().unwrap()
1270 let ch_len = ch.len_utf8();
1273 del_bytes += ch_len;
1274 } else if del_bytes > 0 {
1276 ptr::copy(self.vec.as_ptr().add(idx),
1277 self.vec.as_mut_ptr().add(idx - del_bytes),
1282 // Point idx to the next char
1287 unsafe { self.vec.set_len(len - del_bytes); }
1291 /// Inserts a character into this `String` at a byte position.
1293 /// This is an `O(n)` operation as it requires copying every element in the
1298 /// Panics if `idx` is larger than the `String`'s length, or if it does not
1299 /// lie on a [`char`] boundary.
1301 /// [`char`]: ../../std/primitive.char.html
1308 /// let mut s = String::with_capacity(3);
1310 /// s.insert(0, 'f');
1311 /// s.insert(1, 'o');
1312 /// s.insert(2, 'o');
1314 /// assert_eq!("foo", s);
1317 #[stable(feature = "rust1", since = "1.0.0")]
1318 pub fn insert(&mut self, idx: usize, ch: char) {
1319 assert!(self.is_char_boundary(idx));
1320 let mut bits = [0; 4];
1321 let bits = ch.encode_utf8(&mut bits).as_bytes();
1324 self.insert_bytes(idx, bits);
1328 unsafe fn insert_bytes(&mut self, idx: usize, bytes: &[u8]) {
1329 let len = self.len();
1330 let amt = bytes.len();
1331 self.vec.reserve(amt);
1333 ptr::copy(self.vec.as_ptr().add(idx),
1334 self.vec.as_mut_ptr().add(idx + amt),
1336 ptr::copy(bytes.as_ptr(),
1337 self.vec.as_mut_ptr().add(idx),
1339 self.vec.set_len(len + amt);
1342 /// Inserts a string slice into this `String` at a byte position.
1344 /// This is an `O(n)` operation as it requires copying every element in the
1349 /// Panics if `idx` is larger than the `String`'s length, or if it does not
1350 /// lie on a [`char`] boundary.
1352 /// [`char`]: ../../std/primitive.char.html
1359 /// let mut s = String::from("bar");
1361 /// s.insert_str(0, "foo");
1363 /// assert_eq!("foobar", s);
1366 #[stable(feature = "insert_str", since = "1.16.0")]
1367 pub fn insert_str(&mut self, idx: usize, string: &str) {
1368 assert!(self.is_char_boundary(idx));
1371 self.insert_bytes(idx, string.as_bytes());
1375 /// Returns a mutable reference to the contents of this `String`.
1379 /// This function is unsafe because it does not check that the bytes passed
1380 /// to it are valid UTF-8. If this constraint is violated, it may cause
1381 /// memory unsafety issues with future users of the `String`, as the rest of
1382 /// the standard library assumes that `String`s are valid UTF-8.
1389 /// let mut s = String::from("hello");
1392 /// let vec = s.as_mut_vec();
1393 /// assert_eq!(&[104, 101, 108, 108, 111][..], &vec[..]);
1397 /// assert_eq!(s, "olleh");
1400 #[stable(feature = "rust1", since = "1.0.0")]
1401 pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1405 /// Returns the length of this `String`, in bytes, not [`char`]s or
1406 /// graphemes. In other words, it may not be what a human considers the
1407 /// length of the string.
1414 /// let a = String::from("foo");
1415 /// assert_eq!(a.len(), 3);
1417 /// let fancy_f = String::from("ฦoo");
1418 /// assert_eq!(fancy_f.len(), 4);
1419 /// assert_eq!(fancy_f.chars().count(), 3);
1422 #[stable(feature = "rust1", since = "1.0.0")]
1423 pub fn len(&self) -> usize {
1427 /// Returns `true` if this `String` has a length of zero, and `false` otherwise.
1434 /// let mut v = String::new();
1435 /// assert!(v.is_empty());
1438 /// assert!(!v.is_empty());
1441 #[stable(feature = "rust1", since = "1.0.0")]
1442 pub fn is_empty(&self) -> bool {
1446 /// Splits the string into two at the given index.
1448 /// Returns a newly allocated `String`. `self` contains bytes `[0, at)`, and
1449 /// the returned `String` contains bytes `[at, len)`. `at` must be on the
1450 /// boundary of a UTF-8 code point.
1452 /// Note that the capacity of `self` does not change.
1456 /// Panics if `at` is not on a `UTF-8` code point boundary, or if it is beyond the last
1457 /// code point of the string.
1463 /// let mut hello = String::from("Hello, World!");
1464 /// let world = hello.split_off(7);
1465 /// assert_eq!(hello, "Hello, ");
1466 /// assert_eq!(world, "World!");
1470 #[stable(feature = "string_split_off", since = "1.16.0")]
1471 pub fn split_off(&mut self, at: usize) -> String {
1472 assert!(self.is_char_boundary(at));
1473 let other = self.vec.split_off(at);
1474 unsafe { String::from_utf8_unchecked(other) }
1477 /// Truncates this `String`, removing all contents.
1479 /// While this means the `String` will have a length of zero, it does not
1480 /// touch its capacity.
1487 /// let mut s = String::from("foo");
1491 /// assert!(s.is_empty());
1492 /// assert_eq!(0, s.len());
1493 /// assert_eq!(3, s.capacity());
1496 #[stable(feature = "rust1", since = "1.0.0")]
1497 pub fn clear(&mut self) {
1501 /// Creates a draining iterator that removes the specified range in the `String`
1502 /// and yields the removed `chars`.
1504 /// Note: The element range is removed even if the iterator is not
1505 /// consumed until the end.
1509 /// Panics if the starting point or end point do not lie on a [`char`]
1510 /// boundary, or if they're out of bounds.
1512 /// [`char`]: ../../std/primitive.char.html
1519 /// let mut s = String::from("ฮฑ is alpha, ฮฒ is beta");
1520 /// let beta_offset = s.find('ฮฒ').unwrap_or(s.len());
1522 /// // Remove the range up until the ฮฒ from the string
1523 /// let t: String = s.drain(..beta_offset).collect();
1524 /// assert_eq!(t, "ฮฑ is alpha, ");
1525 /// assert_eq!(s, "ฮฒ is beta");
1527 /// // A full range clears the string
1529 /// assert_eq!(s, "");
1531 #[stable(feature = "drain", since = "1.6.0")]
1532 pub fn drain<R>(&mut self, range: R) -> Drain<'_>
1533 where R: RangeBounds<usize>
1537 // The String version of Drain does not have the memory safety issues
1538 // of the vector version. The data is just plain bytes.
1539 // Because the range removal happens in Drop, if the Drain iterator is leaked,
1540 // the removal will not happen.
1541 let len = self.len();
1542 let start = match range.start_bound() {
1544 Excluded(&n) => n + 1,
1547 let end = match range.end_bound() {
1548 Included(&n) => n + 1,
1553 // Take out two simultaneous borrows. The &mut String won't be accessed
1554 // until iteration is over, in Drop.
1555 let self_ptr = self as *mut _;
1556 // slicing does the appropriate bounds checks
1557 let chars_iter = self[start..end].chars();
1567 /// Removes the specified range in the string,
1568 /// and replaces it with the given string.
1569 /// The given string doesn't need to be the same length as the range.
1573 /// Panics if the starting point or end point do not lie on a [`char`]
1574 /// boundary, or if they're out of bounds.
1576 /// [`char`]: ../../std/primitive.char.html
1577 /// [`Vec::splice`]: ../../std/vec/struct.Vec.html#method.splice
1584 /// let mut s = String::from("ฮฑ is alpha, ฮฒ is beta");
1585 /// let beta_offset = s.find('ฮฒ').unwrap_or(s.len());
1587 /// // Replace the range up until the ฮฒ from the string
1588 /// s.replace_range(..beta_offset, "ฮ is capital alpha; ");
1589 /// assert_eq!(s, "ฮ is capital alpha; ฮฒ is beta");
1591 #[stable(feature = "splice", since = "1.27.0")]
1592 pub fn replace_range<R>(&mut self, range: R, replace_with: &str)
1593 where R: RangeBounds<usize>
1597 // Replace_range does not have the memory safety issues of a vector Splice.
1598 // of the vector version. The data is just plain bytes.
1600 match range.start_bound() {
1601 Included(&n) => assert!(self.is_char_boundary(n)),
1602 Excluded(&n) => assert!(self.is_char_boundary(n + 1)),
1605 match range.end_bound() {
1606 Included(&n) => assert!(self.is_char_boundary(n + 1)),
1607 Excluded(&n) => assert!(self.is_char_boundary(n)),
1613 }.splice(range, replace_with.bytes());
1616 /// Converts this `String` into a [`Box`]`<`[`str`]`>`.
1618 /// This will drop any excess capacity.
1620 /// [`Box`]: ../../std/boxed/struct.Box.html
1621 /// [`str`]: ../../std/primitive.str.html
1628 /// let s = String::from("hello");
1630 /// let b = s.into_boxed_str();
1632 #[stable(feature = "box_str", since = "1.4.0")]
1634 pub fn into_boxed_str(self) -> Box<str> {
1635 let slice = self.vec.into_boxed_slice();
1636 unsafe { from_boxed_utf8_unchecked(slice) }
1640 impl FromUtf8Error {
1641 /// Returns a slice of [`u8`]s bytes that were attempted to convert to a `String`.
1648 /// // some invalid bytes, in a vector
1649 /// let bytes = vec![0, 159];
1651 /// let value = String::from_utf8(bytes);
1653 /// assert_eq!(&[0, 159], value.unwrap_err().as_bytes());
1655 #[stable(feature = "from_utf8_error_as_bytes", since = "1.26.0")]
1656 pub fn as_bytes(&self) -> &[u8] {
1660 /// Returns the bytes that were attempted to convert to a `String`.
1662 /// This method is carefully constructed to avoid allocation. It will
1663 /// consume the error, moving out the bytes, so that a copy of the bytes
1664 /// does not need to be made.
1671 /// // some invalid bytes, in a vector
1672 /// let bytes = vec![0, 159];
1674 /// let value = String::from_utf8(bytes);
1676 /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
1678 #[stable(feature = "rust1", since = "1.0.0")]
1679 pub fn into_bytes(self) -> Vec<u8> {
1683 /// Fetch a `Utf8Error` to get more details about the conversion failure.
1685 /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
1686 /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
1687 /// an analogue to `FromUtf8Error`. See its documentation for more details
1690 /// [`Utf8Error`]: ../../std/str/struct.Utf8Error.html
1691 /// [`std::str`]: ../../std/str/index.html
1692 /// [`u8`]: ../../std/primitive.u8.html
1693 /// [`&str`]: ../../std/primitive.str.html
1700 /// // some invalid bytes, in a vector
1701 /// let bytes = vec![0, 159];
1703 /// let error = String::from_utf8(bytes).unwrap_err().utf8_error();
1705 /// // the first byte is invalid here
1706 /// assert_eq!(1, error.valid_up_to());
1708 #[stable(feature = "rust1", since = "1.0.0")]
1709 pub fn utf8_error(&self) -> Utf8Error {
1714 #[stable(feature = "rust1", since = "1.0.0")]
1715 impl fmt::Display for FromUtf8Error {
1716 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1717 fmt::Display::fmt(&self.error, f)
1721 #[stable(feature = "rust1", since = "1.0.0")]
1722 impl fmt::Display for FromUtf16Error {
1723 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1724 fmt::Display::fmt("invalid utf-16: lone surrogate found", f)
1728 #[stable(feature = "rust1", since = "1.0.0")]
1729 impl Clone for String {
1730 fn clone(&self) -> Self {
1731 String { vec: self.vec.clone() }
1734 fn clone_from(&mut self, source: &Self) {
1735 self.vec.clone_from(&source.vec);
1739 #[stable(feature = "rust1", since = "1.0.0")]
1740 impl FromIterator<char> for String {
1741 fn from_iter<I: IntoIterator<Item = char>>(iter: I) -> String {
1742 let mut buf = String::new();
1748 #[stable(feature = "string_from_iter_by_ref", since = "1.17.0")]
1749 impl<'a> FromIterator<&'a char> for String {
1750 fn from_iter<I: IntoIterator<Item = &'a char>>(iter: I) -> String {
1751 let mut buf = String::new();
1757 #[stable(feature = "rust1", since = "1.0.0")]
1758 impl<'a> FromIterator<&'a str> for String {
1759 fn from_iter<I: IntoIterator<Item = &'a str>>(iter: I) -> String {
1760 let mut buf = String::new();
1766 #[stable(feature = "extend_string", since = "1.4.0")]
1767 impl FromIterator<String> for String {
1768 fn from_iter<I: IntoIterator<Item = String>>(iter: I) -> String {
1769 let mut iterator = iter.into_iter();
1771 // Because we're iterating over `String`s, we can avoid at least
1772 // one allocation by getting the first string from the iterator
1773 // and appending to it all the subsequent strings.
1774 match iterator.next() {
1775 None => String::new(),
1777 buf.extend(iterator);
1784 #[stable(feature = "herd_cows", since = "1.19.0")]
1785 impl<'a> FromIterator<Cow<'a, str>> for String {
1786 fn from_iter<I: IntoIterator<Item = Cow<'a, str>>>(iter: I) -> String {
1787 let mut iterator = iter.into_iter();
1789 // Because we're iterating over CoWs, we can (potentially) avoid at least
1790 // one allocation by getting the first item and appending to it all the
1791 // subsequent items.
1792 match iterator.next() {
1793 None => String::new(),
1795 let mut buf = cow.into_owned();
1796 buf.extend(iterator);
1803 #[stable(feature = "rust1", since = "1.0.0")]
1804 impl Extend<char> for String {
1805 fn extend<I: IntoIterator<Item = char>>(&mut self, iter: I) {
1806 let iterator = iter.into_iter();
1807 let (lower_bound, _) = iterator.size_hint();
1808 self.reserve(lower_bound);
1809 iterator.for_each(move |c| self.push(c));
1813 #[stable(feature = "extend_ref", since = "1.2.0")]
1814 impl<'a> Extend<&'a char> for String {
1815 fn extend<I: IntoIterator<Item = &'a char>>(&mut self, iter: I) {
1816 self.extend(iter.into_iter().cloned());
1820 #[stable(feature = "rust1", since = "1.0.0")]
1821 impl<'a> Extend<&'a str> for String {
1822 fn extend<I: IntoIterator<Item = &'a str>>(&mut self, iter: I) {
1823 iter.into_iter().for_each(move |s| self.push_str(s));
1827 #[stable(feature = "extend_string", since = "1.4.0")]
1828 impl Extend<String> for String {
1829 fn extend<I: IntoIterator<Item = String>>(&mut self, iter: I) {
1830 iter.into_iter().for_each(move |s| self.push_str(&s));
1834 #[stable(feature = "herd_cows", since = "1.19.0")]
1835 impl<'a> Extend<Cow<'a, str>> for String {
1836 fn extend<I: IntoIterator<Item = Cow<'a, str>>>(&mut self, iter: I) {
1837 iter.into_iter().for_each(move |s| self.push_str(&s));
1841 /// A convenience impl that delegates to the impl for `&str`
1842 #[unstable(feature = "pattern",
1843 reason = "API not fully fleshed out and ready to be stabilized",
1845 impl<'a, 'b> Pattern<'a> for &'b String {
1846 type Searcher = <&'b str as Pattern<'a>>::Searcher;
1848 fn into_searcher(self, haystack: &'a str) -> <&'b str as Pattern<'a>>::Searcher {
1849 self[..].into_searcher(haystack)
1853 fn is_contained_in(self, haystack: &'a str) -> bool {
1854 self[..].is_contained_in(haystack)
1858 fn is_prefix_of(self, haystack: &'a str) -> bool {
1859 self[..].is_prefix_of(haystack)
1863 #[stable(feature = "rust1", since = "1.0.0")]
1864 impl PartialEq for String {
1866 fn eq(&self, other: &String) -> bool {
1867 PartialEq::eq(&self[..], &other[..])
1870 fn ne(&self, other: &String) -> bool {
1871 PartialEq::ne(&self[..], &other[..])
1875 macro_rules! impl_eq {
1876 ($lhs:ty, $rhs: ty) => {
1877 #[stable(feature = "rust1", since = "1.0.0")]
1878 #[allow(unused_lifetimes)]
1879 impl<'a, 'b> PartialEq<$rhs> for $lhs {
1881 fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
1883 fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
1886 #[stable(feature = "rust1", since = "1.0.0")]
1887 #[allow(unused_lifetimes)]
1888 impl<'a, 'b> PartialEq<$lhs> for $rhs {
1890 fn eq(&self, other: &$lhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
1892 fn ne(&self, other: &$lhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
1898 impl_eq! { String, str }
1899 impl_eq! { String, &'a str }
1900 impl_eq! { Cow<'a, str>, str }
1901 impl_eq! { Cow<'a, str>, &'b str }
1902 impl_eq! { Cow<'a, str>, String }
1904 #[stable(feature = "rust1", since = "1.0.0")]
1905 impl Default for String {
1906 /// Creates an empty `String`.
1908 fn default() -> String {
1913 #[stable(feature = "rust1", since = "1.0.0")]
1914 impl fmt::Display for String {
1916 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1917 fmt::Display::fmt(&**self, f)
1921 #[stable(feature = "rust1", since = "1.0.0")]
1922 impl fmt::Debug for String {
1924 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1925 fmt::Debug::fmt(&**self, f)
1929 #[stable(feature = "rust1", since = "1.0.0")]
1930 impl hash::Hash for String {
1932 fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
1933 (**self).hash(hasher)
1937 /// Implements the `+` operator for concatenating two strings.
1939 /// This consumes the `String` on the left-hand side and re-uses its buffer (growing it if
1940 /// necessary). This is done to avoid allocating a new `String` and copying the entire contents on
1941 /// every operation, which would lead to `O(n^2)` running time when building an `n`-byte string by
1942 /// repeated concatenation.
1944 /// The string on the right-hand side is only borrowed; its contents are copied into the returned
1949 /// Concatenating two `String`s takes the first by value and borrows the second:
1952 /// let a = String::from("hello");
1953 /// let b = String::from(" world");
1955 /// // `a` is moved and can no longer be used here.
1958 /// If you want to keep using the first `String`, you can clone it and append to the clone instead:
1961 /// let a = String::from("hello");
1962 /// let b = String::from(" world");
1963 /// let c = a.clone() + &b;
1964 /// // `a` is still valid here.
1967 /// Concatenating `&str` slices can be done by converting the first to a `String`:
1970 /// let a = "hello";
1971 /// let b = " world";
1972 /// let c = a.to_string() + b;
1974 #[stable(feature = "rust1", since = "1.0.0")]
1975 impl Add<&str> for String {
1976 type Output = String;
1979 fn add(mut self, other: &str) -> String {
1980 self.push_str(other);
1985 /// Implements the `+=` operator for appending to a `String`.
1987 /// This has the same behavior as the [`push_str`][String::push_str] method.
1988 #[stable(feature = "stringaddassign", since = "1.12.0")]
1989 impl AddAssign<&str> for String {
1991 fn add_assign(&mut self, other: &str) {
1992 self.push_str(other);
1996 #[stable(feature = "rust1", since = "1.0.0")]
1997 impl ops::Index<ops::Range<usize>> for String {
2001 fn index(&self, index: ops::Range<usize>) -> &str {
2005 #[stable(feature = "rust1", since = "1.0.0")]
2006 impl ops::Index<ops::RangeTo<usize>> for String {
2010 fn index(&self, index: ops::RangeTo<usize>) -> &str {
2014 #[stable(feature = "rust1", since = "1.0.0")]
2015 impl ops::Index<ops::RangeFrom<usize>> for String {
2019 fn index(&self, index: ops::RangeFrom<usize>) -> &str {
2023 #[stable(feature = "rust1", since = "1.0.0")]
2024 impl ops::Index<ops::RangeFull> for String {
2028 fn index(&self, _index: ops::RangeFull) -> &str {
2029 unsafe { str::from_utf8_unchecked(&self.vec) }
2032 #[stable(feature = "inclusive_range", since = "1.26.0")]
2033 impl ops::Index<ops::RangeInclusive<usize>> for String {
2037 fn index(&self, index: ops::RangeInclusive<usize>) -> &str {
2038 Index::index(&**self, index)
2041 #[stable(feature = "inclusive_range", since = "1.26.0")]
2042 impl ops::Index<ops::RangeToInclusive<usize>> for String {
2046 fn index(&self, index: ops::RangeToInclusive<usize>) -> &str {
2047 Index::index(&**self, index)
2051 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2052 impl ops::IndexMut<ops::Range<usize>> for String {
2054 fn index_mut(&mut self, index: ops::Range<usize>) -> &mut str {
2055 &mut self[..][index]
2058 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2059 impl ops::IndexMut<ops::RangeTo<usize>> for String {
2061 fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut str {
2062 &mut self[..][index]
2065 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2066 impl ops::IndexMut<ops::RangeFrom<usize>> for String {
2068 fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut str {
2069 &mut self[..][index]
2072 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2073 impl ops::IndexMut<ops::RangeFull> for String {
2075 fn index_mut(&mut self, _index: ops::RangeFull) -> &mut str {
2076 unsafe { str::from_utf8_unchecked_mut(&mut *self.vec) }
2079 #[stable(feature = "inclusive_range", since = "1.26.0")]
2080 impl ops::IndexMut<ops::RangeInclusive<usize>> for String {
2082 fn index_mut(&mut self, index: ops::RangeInclusive<usize>) -> &mut str {
2083 IndexMut::index_mut(&mut **self, index)
2086 #[stable(feature = "inclusive_range", since = "1.26.0")]
2087 impl ops::IndexMut<ops::RangeToInclusive<usize>> for String {
2089 fn index_mut(&mut self, index: ops::RangeToInclusive<usize>) -> &mut str {
2090 IndexMut::index_mut(&mut **self, index)
2094 #[stable(feature = "rust1", since = "1.0.0")]
2095 impl ops::Deref for String {
2099 fn deref(&self) -> &str {
2100 unsafe { str::from_utf8_unchecked(&self.vec) }
2104 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2105 impl ops::DerefMut for String {
2107 fn deref_mut(&mut self) -> &mut str {
2108 unsafe { str::from_utf8_unchecked_mut(&mut *self.vec) }
2112 /// An error when parsing a `String`.
2114 /// This `enum` is slightly awkward: it will never actually exist. This error is
2115 /// part of the type signature of the implementation of [`FromStr`] on
2116 /// [`String`]. The return type of [`from_str`], requires that an error be
2117 /// defined, but, given that a [`String`] can always be made into a new
2118 /// [`String`] without error, this type will never actually be returned. As
2119 /// such, it is only here to satisfy said signature, and is useless otherwise.
2121 /// [`FromStr`]: ../../std/str/trait.FromStr.html
2122 /// [`String`]: struct.String.html
2123 /// [`from_str`]: ../../std/str/trait.FromStr.html#tymethod.from_str
2124 #[stable(feature = "str_parse_error", since = "1.5.0")]
2125 pub type ParseError = core::convert::Infallible;
2127 #[stable(feature = "rust1", since = "1.0.0")]
2128 impl FromStr for String {
2129 type Err = core::convert::Infallible;
2131 fn from_str(s: &str) -> Result<String, ParseError> {
2137 /// A trait for converting a value to a `String`.
2139 /// This trait is automatically implemented for any type which implements the
2140 /// [`Display`] trait. As such, `ToString` shouldn't be implemented directly:
2141 /// [`Display`] should be implemented instead, and you get the `ToString`
2142 /// implementation for free.
2144 /// [`Display`]: ../../std/fmt/trait.Display.html
2145 #[stable(feature = "rust1", since = "1.0.0")]
2146 pub trait ToString {
2147 /// Converts the given value to a `String`.
2155 /// let five = String::from("5");
2157 /// assert_eq!(five, i.to_string());
2159 #[rustc_conversion_suggestion]
2160 #[stable(feature = "rust1", since = "1.0.0")]
2161 fn to_string(&self) -> String;
2166 /// In this implementation, the `to_string` method panics
2167 /// if the `Display` implementation returns an error.
2168 /// This indicates an incorrect `Display` implementation
2169 /// since `fmt::Write for String` never returns an error itself.
2170 #[stable(feature = "rust1", since = "1.0.0")]
2171 impl<T: fmt::Display + ?Sized> ToString for T {
2173 default fn to_string(&self) -> String {
2175 let mut buf = String::new();
2176 buf.write_fmt(format_args!("{}", self))
2177 .expect("a Display implementation returned an error unexpectedly");
2178 buf.shrink_to_fit();
2183 #[stable(feature = "str_to_string_specialization", since = "1.9.0")]
2184 impl ToString for str {
2186 fn to_string(&self) -> String {
2191 #[stable(feature = "cow_str_to_string_specialization", since = "1.17.0")]
2192 impl ToString for Cow<'_, str> {
2194 fn to_string(&self) -> String {
2199 #[stable(feature = "string_to_string_specialization", since = "1.17.0")]
2200 impl ToString for String {
2202 fn to_string(&self) -> String {
2207 #[stable(feature = "rust1", since = "1.0.0")]
2208 impl AsRef<str> for String {
2210 fn as_ref(&self) -> &str {
2215 #[stable(feature = "rust1", since = "1.0.0")]
2216 impl AsRef<[u8]> for String {
2218 fn as_ref(&self) -> &[u8] {
2223 #[stable(feature = "rust1", since = "1.0.0")]
2224 impl From<&str> for String {
2226 fn from(s: &str) -> String {
2231 #[stable(feature = "from_ref_string", since = "1.35.0")]
2232 impl From<&String> for String {
2234 fn from(s: &String) -> String {
2239 // note: test pulls in libstd, which causes errors here
2241 #[stable(feature = "string_from_box", since = "1.18.0")]
2242 impl From<Box<str>> for String {
2243 /// Converts the given boxed `str` slice to a `String`.
2244 /// It is notable that the `str` slice is owned.
2251 /// let s1: String = String::from("hello world");
2252 /// let s2: Box<str> = s1.into_boxed_str();
2253 /// let s3: String = String::from(s2);
2255 /// assert_eq!("hello world", s3)
2257 fn from(s: Box<str>) -> String {
2262 #[stable(feature = "box_from_str", since = "1.20.0")]
2263 impl From<String> for Box<str> {
2264 /// Converts the given `String` to a boxed `str` slice that is owned.
2271 /// let s1: String = String::from("hello world");
2272 /// let s2: Box<str> = Box::from(s1);
2273 /// let s3: String = String::from(s2);
2275 /// assert_eq!("hello world", s3)
2277 fn from(s: String) -> Box<str> {
2282 #[stable(feature = "string_from_cow_str", since = "1.14.0")]
2283 impl<'a> From<Cow<'a, str>> for String {
2284 fn from(s: Cow<'a, str>) -> String {
2289 #[stable(feature = "rust1", since = "1.0.0")]
2290 impl<'a> From<&'a str> for Cow<'a, str> {
2292 fn from(s: &'a str) -> Cow<'a, str> {
2297 #[stable(feature = "rust1", since = "1.0.0")]
2298 impl<'a> From<String> for Cow<'a, str> {
2300 fn from(s: String) -> Cow<'a, str> {
2305 #[stable(feature = "cow_from_string_ref", since = "1.28.0")]
2306 impl<'a> From<&'a String> for Cow<'a, str> {
2308 fn from(s: &'a String) -> Cow<'a, str> {
2309 Cow::Borrowed(s.as_str())
2313 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2314 impl<'a> FromIterator<char> for Cow<'a, str> {
2315 fn from_iter<I: IntoIterator<Item = char>>(it: I) -> Cow<'a, str> {
2316 Cow::Owned(FromIterator::from_iter(it))
2320 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2321 impl<'a, 'b> FromIterator<&'b str> for Cow<'a, str> {
2322 fn from_iter<I: IntoIterator<Item = &'b str>>(it: I) -> Cow<'a, str> {
2323 Cow::Owned(FromIterator::from_iter(it))
2327 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2328 impl<'a> FromIterator<String> for Cow<'a, str> {
2329 fn from_iter<I: IntoIterator<Item = String>>(it: I) -> Cow<'a, str> {
2330 Cow::Owned(FromIterator::from_iter(it))
2334 #[stable(feature = "from_string_for_vec_u8", since = "1.14.0")]
2335 impl From<String> for Vec<u8> {
2336 /// Converts the given `String` to a vector `Vec` that holds values of type `u8`.
2343 /// let s1 = String::from("hello world");
2344 /// let v1 = Vec::from(s1);
2347 /// println!("{}", b);
2350 fn from(string: String) -> Vec<u8> {
2355 #[stable(feature = "rust1", since = "1.0.0")]
2356 impl fmt::Write for String {
2358 fn write_str(&mut self, s: &str) -> fmt::Result {
2364 fn write_char(&mut self, c: char) -> fmt::Result {
2370 /// A draining iterator for `String`.
2372 /// This struct is created by the [`drain`] method on [`String`]. See its
2373 /// documentation for more.
2375 /// [`drain`]: struct.String.html#method.drain
2376 /// [`String`]: struct.String.html
2377 #[stable(feature = "drain", since = "1.6.0")]
2378 pub struct Drain<'a> {
2379 /// Will be used as &'a mut String in the destructor
2380 string: *mut String,
2381 /// Start of part to remove
2383 /// End of part to remove
2385 /// Current remaining range to remove
2389 #[stable(feature = "collection_debug", since = "1.17.0")]
2390 impl fmt::Debug for Drain<'_> {
2391 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2392 f.pad("Drain { .. }")
2396 #[stable(feature = "drain", since = "1.6.0")]
2397 unsafe impl Sync for Drain<'_> {}
2398 #[stable(feature = "drain", since = "1.6.0")]
2399 unsafe impl Send for Drain<'_> {}
2401 #[stable(feature = "drain", since = "1.6.0")]
2402 impl Drop for Drain<'_> {
2403 fn drop(&mut self) {
2405 // Use Vec::drain. "Reaffirm" the bounds checks to avoid
2406 // panic code being inserted again.
2407 let self_vec = (*self.string).as_mut_vec();
2408 if self.start <= self.end && self.end <= self_vec.len() {
2409 self_vec.drain(self.start..self.end);
2415 #[stable(feature = "drain", since = "1.6.0")]
2416 impl Iterator for Drain<'_> {
2420 fn next(&mut self) -> Option<char> {
2424 fn size_hint(&self) -> (usize, Option<usize>) {
2425 self.iter.size_hint()
2429 fn last(mut self) -> Option<char> {
2434 #[stable(feature = "drain", since = "1.6.0")]
2435 impl DoubleEndedIterator for Drain<'_> {
2437 fn next_back(&mut self) -> Option<char> {
2438 self.iter.next_back()
2442 #[stable(feature = "fused", since = "1.26.0")]
2443 impl FusedIterator for Drain<'_> {}