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::Bound::{Excluded, Included, Unbounded};
54 use core::ops::{self, Add, AddAssign, Index, IndexMut, RangeBounds};
56 use core::str::{lossy, pattern::Pattern};
58 use crate::borrow::{Cow, ToOwned};
59 use crate::boxed::Box;
60 use crate::collections::TryReserveError;
61 use crate::str::{self, from_boxed_utf8_unchecked, Chars, FromStr, Utf8Error};
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")]
322 #[derive(Debug, Clone, PartialEq, Eq)]
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 #[rustc_const_stable(feature = "const_string_new", since = "1.32.0")]
371 #[stable(feature = "rust1", since = "1.0.0")]
372 pub const fn new() -> String {
373 String { vec: Vec::new() }
376 /// Creates a new empty `String` with a particular capacity.
378 /// `String`s have an internal buffer to hold their data. The capacity is
379 /// the length of that buffer, and can be queried with the [`capacity`]
380 /// method. This method creates an empty `String`, but one with an initial
381 /// buffer that can hold `capacity` bytes. This is useful when you may be
382 /// appending a bunch of data to the `String`, reducing the number of
383 /// reallocations it needs to do.
385 /// [`capacity`]: #method.capacity
387 /// If the given capacity is `0`, no allocation will occur, and this method
388 /// is identical to the [`new`] method.
390 /// [`new`]: #method.new
397 /// let mut s = String::with_capacity(10);
399 /// // The String contains no chars, even though it has capacity for more
400 /// assert_eq!(s.len(), 0);
402 /// // These are all done without reallocating...
403 /// let cap = s.capacity();
408 /// assert_eq!(s.capacity(), cap);
410 /// // ...but this may make the string reallocate
414 #[stable(feature = "rust1", since = "1.0.0")]
415 pub fn with_capacity(capacity: usize) -> String {
416 String { vec: Vec::with_capacity(capacity) }
419 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
420 // required for this method definition, is not available. Since we don't
421 // require this method for testing purposes, I'll just stub it
422 // NB see the slice::hack module in slice.rs for more information
425 pub fn from_str(_: &str) -> String {
426 panic!("not available with cfg(test)");
429 /// Converts a vector of bytes to a `String`.
431 /// A string ([`String`]) is made of bytes ([`u8`]), and a vector of bytes
432 /// ([`Vec<u8>`]) is made of bytes, so this function converts between the
433 /// two. Not all byte slices are valid `String`s, however: `String`
434 /// requires that it is valid UTF-8. `from_utf8()` checks to ensure that
435 /// the bytes are valid UTF-8, and then does the conversion.
437 /// If you are sure that the byte slice is valid UTF-8, and you don't want
438 /// to incur the overhead of the validity check, there is an unsafe version
439 /// of this function, [`from_utf8_unchecked`], which has the same behavior
440 /// but skips the check.
442 /// This method will take care to not copy the vector, for efficiency's
445 /// If you need a [`&str`] instead of a `String`, consider
446 /// [`str::from_utf8`].
448 /// The inverse of this method is [`into_bytes`].
452 /// Returns [`Err`] if the slice is not UTF-8 with a description as to why the
453 /// provided bytes are not UTF-8. The vector you moved in is also included.
460 /// // some bytes, in a vector
461 /// let sparkle_heart = vec![240, 159, 146, 150];
463 /// // We know these bytes are valid, so we'll use `unwrap()`.
464 /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
466 /// assert_eq!("💖", sparkle_heart);
472 /// // some invalid bytes, in a vector
473 /// let sparkle_heart = vec![0, 159, 146, 150];
475 /// assert!(String::from_utf8(sparkle_heart).is_err());
478 /// See the docs for [`FromUtf8Error`] for more details on what you can do
481 /// [`from_utf8_unchecked`]: struct.String.html#method.from_utf8_unchecked
482 /// [`String`]: struct.String.html
483 /// [`u8`]: ../../std/primitive.u8.html
484 /// [`Vec<u8>`]: ../../std/vec/struct.Vec.html
485 /// [`&str`]: ../../std/primitive.str.html
486 /// [`str::from_utf8`]: ../../std/str/fn.from_utf8.html
487 /// [`into_bytes`]: struct.String.html#method.into_bytes
488 /// [`FromUtf8Error`]: struct.FromUtf8Error.html
489 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
491 #[stable(feature = "rust1", since = "1.0.0")]
492 pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error> {
493 match str::from_utf8(&vec) {
494 Ok(..) => Ok(String { vec }),
495 Err(e) => Err(FromUtf8Error { bytes: vec, error: e }),
499 /// Converts a slice of bytes to a string, including invalid characters.
501 /// Strings are made of bytes ([`u8`]), and a slice of bytes
502 /// ([`&[u8]`][byteslice]) is made of bytes, so this function converts
503 /// between the two. Not all byte slices are valid strings, however: strings
504 /// are required to be valid UTF-8. During this conversion,
505 /// `from_utf8_lossy()` will replace any invalid UTF-8 sequences with
506 /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD], which looks like this: �
508 /// [`u8`]: ../../std/primitive.u8.html
509 /// [byteslice]: ../../std/primitive.slice.html
510 /// [U+FFFD]: ../char/constant.REPLACEMENT_CHARACTER.html
512 /// If you are sure that the byte slice is valid UTF-8, and you don't want
513 /// to incur the overhead of the conversion, there is an unsafe version
514 /// of this function, [`from_utf8_unchecked`], which has the same behavior
515 /// but skips the checks.
517 /// [`from_utf8_unchecked`]: struct.String.html#method.from_utf8_unchecked
519 /// This function returns a [`Cow<'a, str>`]. If our byte slice is invalid
520 /// UTF-8, then we need to insert the replacement characters, which will
521 /// change the size of the string, and hence, require a `String`. But if
522 /// it's already valid UTF-8, we don't need a new allocation. This return
523 /// type allows us to handle both cases.
525 /// [`Cow<'a, str>`]: ../../std/borrow/enum.Cow.html
532 /// // some bytes, in a vector
533 /// let sparkle_heart = vec![240, 159, 146, 150];
535 /// let sparkle_heart = String::from_utf8_lossy(&sparkle_heart);
537 /// assert_eq!("💖", sparkle_heart);
543 /// // some invalid bytes
544 /// let input = b"Hello \xF0\x90\x80World";
545 /// let output = String::from_utf8_lossy(input);
547 /// assert_eq!("Hello �World", output);
549 #[stable(feature = "rust1", since = "1.0.0")]
550 pub fn from_utf8_lossy(v: &[u8]) -> Cow<'_, str> {
551 let mut iter = lossy::Utf8Lossy::from_bytes(v).chunks();
553 let (first_valid, first_broken) = if let Some(chunk) = iter.next() {
554 let lossy::Utf8LossyChunk { valid, broken } = chunk;
555 if valid.len() == v.len() {
556 debug_assert!(broken.is_empty());
557 return Cow::Borrowed(valid);
561 return Cow::Borrowed("");
564 const REPLACEMENT: &str = "\u{FFFD}";
566 let mut res = String::with_capacity(v.len());
567 res.push_str(first_valid);
568 if !first_broken.is_empty() {
569 res.push_str(REPLACEMENT);
572 for lossy::Utf8LossyChunk { valid, broken } in iter {
574 if !broken.is_empty() {
575 res.push_str(REPLACEMENT);
582 /// Decode a UTF-16 encoded vector `v` into a `String`, returning [`Err`]
583 /// if `v` contains any invalid data.
585 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
593 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
594 /// 0x0073, 0x0069, 0x0063];
595 /// assert_eq!(String::from("𝄞music"),
596 /// String::from_utf16(v).unwrap());
598 /// // 𝄞mu<invalid>ic
599 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
600 /// 0xD800, 0x0069, 0x0063];
601 /// assert!(String::from_utf16(v).is_err());
603 #[stable(feature = "rust1", since = "1.0.0")]
604 pub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error> {
605 // This isn't done via collect::<Result<_, _>>() for performance reasons.
606 // FIXME: the function can be simplified again when #48994 is closed.
607 let mut ret = String::with_capacity(v.len());
608 for c in decode_utf16(v.iter().cloned()) {
612 return Err(FromUtf16Error(()));
618 /// Decode a UTF-16 encoded slice `v` into a `String`, replacing
619 /// invalid data with [the replacement character (`U+FFFD`)][U+FFFD].
621 /// Unlike [`from_utf8_lossy`] which returns a [`Cow<'a, str>`],
622 /// `from_utf16_lossy` returns a `String` since the UTF-16 to UTF-8
623 /// conversion requires a memory allocation.
625 /// [`from_utf8_lossy`]: #method.from_utf8_lossy
626 /// [`Cow<'a, str>`]: ../borrow/enum.Cow.html
627 /// [U+FFFD]: ../char/constant.REPLACEMENT_CHARACTER.html
634 /// // 𝄞mus<invalid>ic<invalid>
635 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
636 /// 0x0073, 0xDD1E, 0x0069, 0x0063,
639 /// assert_eq!(String::from("𝄞mus\u{FFFD}ic\u{FFFD}"),
640 /// String::from_utf16_lossy(v));
643 #[stable(feature = "rust1", since = "1.0.0")]
644 pub fn from_utf16_lossy(v: &[u16]) -> String {
645 decode_utf16(v.iter().cloned()).map(|r| r.unwrap_or(REPLACEMENT_CHARACTER)).collect()
648 /// Decomposes a `String` into its raw components.
650 /// Returns the raw pointer to the underlying data, the length of
651 /// the string (in bytes), and the allocated capacity of the data
652 /// (in bytes). These are the same arguments in the same order as
653 /// the arguments to [`from_raw_parts`].
655 /// After calling this function, the caller is responsible for the
656 /// memory previously managed by the `String`. The only way to do
657 /// this is to convert the raw pointer, length, and capacity back
658 /// into a `String` with the [`from_raw_parts`] function, allowing
659 /// the destructor to perform the cleanup.
661 /// [`from_raw_parts`]: #method.from_raw_parts
666 /// #![feature(vec_into_raw_parts)]
667 /// let s = String::from("hello");
669 /// let (ptr, len, cap) = s.into_raw_parts();
671 /// let rebuilt = unsafe { String::from_raw_parts(ptr, len, cap) };
672 /// assert_eq!(rebuilt, "hello");
674 #[unstable(feature = "vec_into_raw_parts", reason = "new API", issue = "65816")]
675 pub fn into_raw_parts(self) -> (*mut u8, usize, usize) {
676 self.vec.into_raw_parts()
679 /// Creates a new `String` from a length, capacity, and pointer.
683 /// This is highly unsafe, due to the number of invariants that aren't
686 /// * The memory at `ptr` needs to have been previously allocated by the
687 /// same allocator the standard library uses, with a required alignment of exactly 1.
688 /// * `length` needs to be less than or equal to `capacity`.
689 /// * `capacity` needs to be the correct value.
691 /// Violating these may cause problems like corrupting the allocator's
692 /// internal data structures.
694 /// The ownership of `ptr` is effectively transferred to the
695 /// `String` which may then deallocate, reallocate or change the
696 /// contents of memory pointed to by the pointer at will. Ensure
697 /// that nothing else uses the pointer after calling this
708 /// let s = String::from("hello");
710 // FIXME Update this when vec_into_raw_parts is stabilized
711 /// // Prevent automatically dropping the String's data
712 /// let mut s = mem::ManuallyDrop::new(s);
714 /// let ptr = s.as_mut_ptr();
715 /// let len = s.len();
716 /// let capacity = s.capacity();
718 /// let s = String::from_raw_parts(ptr, len, capacity);
720 /// assert_eq!(String::from("hello"), s);
724 #[stable(feature = "rust1", since = "1.0.0")]
725 pub unsafe fn from_raw_parts(buf: *mut u8, length: usize, capacity: usize) -> String {
726 String { vec: Vec::from_raw_parts(buf, length, capacity) }
729 /// Converts a vector of bytes to a `String` without checking that the
730 /// string contains valid UTF-8.
732 /// See the safe version, [`from_utf8`], for more details.
734 /// [`from_utf8`]: struct.String.html#method.from_utf8
738 /// This function is unsafe because it does not check that the bytes passed
739 /// to it are valid UTF-8. If this constraint is violated, it may cause
740 /// memory unsafety issues with future users of the `String`, as the rest of
741 /// the standard library assumes that `String`s are valid UTF-8.
748 /// // some bytes, in a vector
749 /// let sparkle_heart = vec![240, 159, 146, 150];
751 /// let sparkle_heart = unsafe {
752 /// String::from_utf8_unchecked(sparkle_heart)
755 /// assert_eq!("💖", sparkle_heart);
758 #[stable(feature = "rust1", since = "1.0.0")]
759 pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String {
760 String { vec: bytes }
763 /// Converts a `String` into a byte vector.
765 /// This consumes the `String`, so we do not need to copy its contents.
772 /// let s = String::from("hello");
773 /// let bytes = s.into_bytes();
775 /// assert_eq!(&[104, 101, 108, 108, 111][..], &bytes[..]);
778 #[stable(feature = "rust1", since = "1.0.0")]
779 pub fn into_bytes(self) -> Vec<u8> {
783 /// Extracts a string slice containing the entire `String`.
790 /// let s = String::from("foo");
792 /// assert_eq!("foo", s.as_str());
795 #[stable(feature = "string_as_str", since = "1.7.0")]
796 pub fn as_str(&self) -> &str {
800 /// Converts a `String` into a mutable string slice.
807 /// let mut s = String::from("foobar");
808 /// let s_mut_str = s.as_mut_str();
810 /// s_mut_str.make_ascii_uppercase();
812 /// assert_eq!("FOOBAR", s_mut_str);
815 #[stable(feature = "string_as_str", since = "1.7.0")]
816 pub fn as_mut_str(&mut self) -> &mut str {
820 /// Appends a given string slice onto the end of this `String`.
827 /// let mut s = String::from("foo");
829 /// s.push_str("bar");
831 /// assert_eq!("foobar", s);
834 #[stable(feature = "rust1", since = "1.0.0")]
835 pub fn push_str(&mut self, string: &str) {
836 self.vec.extend_from_slice(string.as_bytes())
839 /// Returns this `String`'s capacity, in bytes.
846 /// let s = String::with_capacity(10);
848 /// assert!(s.capacity() >= 10);
851 #[stable(feature = "rust1", since = "1.0.0")]
852 pub fn capacity(&self) -> usize {
856 /// Ensures that this `String`'s capacity is at least `additional` bytes
857 /// larger than its length.
859 /// The capacity may be increased by more than `additional` bytes if it
860 /// chooses, to prevent frequent reallocations.
862 /// If you do not want this "at least" behavior, see the [`reserve_exact`]
867 /// Panics if the new capacity overflows [`usize`].
869 /// [`reserve_exact`]: struct.String.html#method.reserve_exact
870 /// [`usize`]: ../../std/primitive.usize.html
877 /// let mut s = String::new();
881 /// assert!(s.capacity() >= 10);
884 /// This may not actually increase the capacity:
887 /// let mut s = String::with_capacity(10);
891 /// // s now has a length of 2 and a capacity of 10
892 /// assert_eq!(2, s.len());
893 /// assert_eq!(10, s.capacity());
895 /// // Since we already have an extra 8 capacity, calling this...
898 /// // ... doesn't actually increase.
899 /// assert_eq!(10, s.capacity());
902 #[stable(feature = "rust1", since = "1.0.0")]
903 pub fn reserve(&mut self, additional: usize) {
904 self.vec.reserve(additional)
907 /// Ensures that this `String`'s capacity is `additional` bytes
908 /// larger than its length.
910 /// Consider using the [`reserve`] method unless you absolutely know
911 /// better than the allocator.
913 /// [`reserve`]: #method.reserve
917 /// Panics if the new capacity overflows `usize`.
924 /// let mut s = String::new();
926 /// s.reserve_exact(10);
928 /// assert!(s.capacity() >= 10);
931 /// This may not actually increase the capacity:
934 /// let mut s = String::with_capacity(10);
938 /// // s now has a length of 2 and a capacity of 10
939 /// assert_eq!(2, s.len());
940 /// assert_eq!(10, s.capacity());
942 /// // Since we already have an extra 8 capacity, calling this...
943 /// s.reserve_exact(8);
945 /// // ... doesn't actually increase.
946 /// assert_eq!(10, s.capacity());
949 #[stable(feature = "rust1", since = "1.0.0")]
950 pub fn reserve_exact(&mut self, additional: usize) {
951 self.vec.reserve_exact(additional)
954 /// Tries to reserve capacity for at least `additional` more elements to be inserted
955 /// in the given `String`. The collection may reserve more space to avoid
956 /// frequent reallocations. After calling `reserve`, capacity will be
957 /// greater than or equal to `self.len() + additional`. Does nothing if
958 /// capacity is already sufficient.
962 /// If the capacity overflows, or the allocator reports a failure, then an error
968 /// #![feature(try_reserve)]
969 /// use std::collections::TryReserveError;
971 /// fn process_data(data: &str) -> Result<String, TryReserveError> {
972 /// let mut output = String::new();
974 /// // Pre-reserve the memory, exiting if we can't
975 /// output.try_reserve(data.len())?;
977 /// // Now we know this can't OOM in the middle of our complex work
978 /// output.push_str(data);
982 /// # process_data("rust").expect("why is the test harness OOMing on 4 bytes?");
984 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
985 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
986 self.vec.try_reserve(additional)
989 /// Tries to reserves the minimum capacity for exactly `additional` more elements to
990 /// be inserted in the given `String`. After calling `reserve_exact`,
991 /// capacity will be greater than or equal to `self.len() + additional`.
992 /// Does nothing if the capacity is already sufficient.
994 /// Note that the allocator may give the collection more space than it
995 /// requests. Therefore, capacity can not be relied upon to be precisely
996 /// minimal. Prefer `reserve` if future insertions are expected.
1000 /// If the capacity overflows, or the allocator reports a failure, then an error
1006 /// #![feature(try_reserve)]
1007 /// use std::collections::TryReserveError;
1009 /// fn process_data(data: &str) -> Result<String, TryReserveError> {
1010 /// let mut output = String::new();
1012 /// // Pre-reserve the memory, exiting if we can't
1013 /// output.try_reserve(data.len())?;
1015 /// // Now we know this can't OOM in the middle of our complex work
1016 /// output.push_str(data);
1020 /// # process_data("rust").expect("why is the test harness OOMing on 4 bytes?");
1022 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
1023 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
1024 self.vec.try_reserve_exact(additional)
1027 /// Shrinks the capacity of this `String` to match its length.
1034 /// let mut s = String::from("foo");
1037 /// assert!(s.capacity() >= 100);
1039 /// s.shrink_to_fit();
1040 /// assert_eq!(3, s.capacity());
1043 #[stable(feature = "rust1", since = "1.0.0")]
1044 pub fn shrink_to_fit(&mut self) {
1045 self.vec.shrink_to_fit()
1048 /// Shrinks the capacity of this `String` with a lower bound.
1050 /// The capacity will remain at least as large as both the length
1051 /// and the supplied value.
1053 /// Panics if the current capacity is smaller than the supplied
1054 /// minimum capacity.
1059 /// #![feature(shrink_to)]
1060 /// let mut s = String::from("foo");
1063 /// assert!(s.capacity() >= 100);
1065 /// s.shrink_to(10);
1066 /// assert!(s.capacity() >= 10);
1068 /// assert!(s.capacity() >= 3);
1071 #[unstable(feature = "shrink_to", reason = "new API", issue = "56431")]
1072 pub fn shrink_to(&mut self, min_capacity: usize) {
1073 self.vec.shrink_to(min_capacity)
1076 /// Appends the given [`char`] to the end of this `String`.
1078 /// [`char`]: ../../std/primitive.char.html
1085 /// let mut s = String::from("abc");
1091 /// assert_eq!("abc123", s);
1094 #[stable(feature = "rust1", since = "1.0.0")]
1095 pub fn push(&mut self, ch: char) {
1096 match ch.len_utf8() {
1097 1 => self.vec.push(ch as u8),
1098 _ => self.vec.extend_from_slice(ch.encode_utf8(&mut [0; 4]).as_bytes()),
1102 /// Returns a byte slice of this `String`'s contents.
1104 /// The inverse of this method is [`from_utf8`].
1106 /// [`from_utf8`]: #method.from_utf8
1113 /// let s = String::from("hello");
1115 /// assert_eq!(&[104, 101, 108, 108, 111], s.as_bytes());
1118 #[stable(feature = "rust1", since = "1.0.0")]
1119 pub fn as_bytes(&self) -> &[u8] {
1123 /// Shortens this `String` to the specified length.
1125 /// If `new_len` is greater than the string's current length, this has no
1128 /// Note that this method has no effect on the allocated capacity
1133 /// Panics if `new_len` does not lie on a [`char`] boundary.
1135 /// [`char`]: ../../std/primitive.char.html
1142 /// let mut s = String::from("hello");
1146 /// assert_eq!("he", s);
1149 #[stable(feature = "rust1", since = "1.0.0")]
1150 pub fn truncate(&mut self, new_len: usize) {
1151 if new_len <= self.len() {
1152 assert!(self.is_char_boundary(new_len));
1153 self.vec.truncate(new_len)
1157 /// Removes the last character from the string buffer and returns it.
1159 /// Returns [`None`] if this `String` is empty.
1161 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1168 /// let mut s = String::from("foo");
1170 /// assert_eq!(s.pop(), Some('o'));
1171 /// assert_eq!(s.pop(), Some('o'));
1172 /// assert_eq!(s.pop(), Some('f'));
1174 /// assert_eq!(s.pop(), None);
1177 #[stable(feature = "rust1", since = "1.0.0")]
1178 pub fn pop(&mut self) -> Option<char> {
1179 let ch = self.chars().rev().next()?;
1180 let newlen = self.len() - ch.len_utf8();
1182 self.vec.set_len(newlen);
1187 /// Removes a [`char`] from this `String` at a byte position and returns it.
1189 /// This is an `O(n)` operation, as it requires copying every element in the
1194 /// Panics if `idx` is larger than or equal to the `String`'s length,
1195 /// or if it does not lie on a [`char`] boundary.
1197 /// [`char`]: ../../std/primitive.char.html
1204 /// let mut s = String::from("foo");
1206 /// assert_eq!(s.remove(0), 'f');
1207 /// assert_eq!(s.remove(1), 'o');
1208 /// assert_eq!(s.remove(0), 'o');
1211 #[stable(feature = "rust1", since = "1.0.0")]
1212 pub fn remove(&mut self, idx: usize) -> char {
1213 let ch = match self[idx..].chars().next() {
1215 None => panic!("cannot remove a char from the end of a string"),
1218 let next = idx + ch.len_utf8();
1219 let len = self.len();
1221 ptr::copy(self.vec.as_ptr().add(next), self.vec.as_mut_ptr().add(idx), len - next);
1222 self.vec.set_len(len - (next - idx));
1227 /// Retains only the characters specified by the predicate.
1229 /// In other words, remove all characters `c` such that `f(c)` returns `false`.
1230 /// This method operates in place, visiting each character exactly once in the
1231 /// original order, and preserves the order of the retained characters.
1236 /// let mut s = String::from("f_o_ob_ar");
1238 /// s.retain(|c| c != '_');
1240 /// assert_eq!(s, "foobar");
1243 /// The exact order may be useful for tracking external state, like an index.
1246 /// let mut s = String::from("abcde");
1247 /// let keep = [false, true, true, false, true];
1249 /// s.retain(|_| (keep[i], i += 1).0);
1250 /// assert_eq!(s, "bce");
1253 #[stable(feature = "string_retain", since = "1.26.0")]
1254 pub fn retain<F>(&mut self, mut f: F)
1256 F: FnMut(char) -> bool,
1258 let len = self.len();
1259 let mut del_bytes = 0;
1263 let ch = unsafe { self.get_unchecked(idx..len).chars().next().unwrap() };
1264 let ch_len = ch.len_utf8();
1267 del_bytes += ch_len;
1268 } else if del_bytes > 0 {
1271 self.vec.as_ptr().add(idx),
1272 self.vec.as_mut_ptr().add(idx - del_bytes),
1278 // Point idx to the next char
1284 self.vec.set_len(len - del_bytes);
1289 /// Inserts a character into this `String` at a byte position.
1291 /// This is an `O(n)` operation as it requires copying every element in the
1296 /// Panics if `idx` is larger than the `String`'s length, or if it does not
1297 /// lie on a [`char`] boundary.
1299 /// [`char`]: ../../std/primitive.char.html
1306 /// let mut s = String::with_capacity(3);
1308 /// s.insert(0, 'f');
1309 /// s.insert(1, 'o');
1310 /// s.insert(2, 'o');
1312 /// assert_eq!("foo", s);
1315 #[stable(feature = "rust1", since = "1.0.0")]
1316 pub fn insert(&mut self, idx: usize, ch: char) {
1317 assert!(self.is_char_boundary(idx));
1318 let mut bits = [0; 4];
1319 let bits = ch.encode_utf8(&mut bits).as_bytes();
1322 self.insert_bytes(idx, bits);
1326 unsafe fn insert_bytes(&mut self, idx: usize, bytes: &[u8]) {
1327 let len = self.len();
1328 let amt = bytes.len();
1329 self.vec.reserve(amt);
1331 ptr::copy(self.vec.as_ptr().add(idx), self.vec.as_mut_ptr().add(idx + amt), len - idx);
1332 ptr::copy(bytes.as_ptr(), self.vec.as_mut_ptr().add(idx), amt);
1333 self.vec.set_len(len + amt);
1336 /// Inserts a string slice into this `String` at a byte position.
1338 /// This is an `O(n)` operation as it requires copying every element in the
1343 /// Panics if `idx` is larger than the `String`'s length, or if it does not
1344 /// lie on a [`char`] boundary.
1346 /// [`char`]: ../../std/primitive.char.html
1353 /// let mut s = String::from("bar");
1355 /// s.insert_str(0, "foo");
1357 /// assert_eq!("foobar", s);
1360 #[stable(feature = "insert_str", since = "1.16.0")]
1361 pub fn insert_str(&mut self, idx: usize, string: &str) {
1362 assert!(self.is_char_boundary(idx));
1365 self.insert_bytes(idx, string.as_bytes());
1369 /// Returns a mutable reference to the contents of this `String`.
1373 /// This function is unsafe because it does not check that the bytes passed
1374 /// to it are valid UTF-8. If this constraint is violated, it may cause
1375 /// memory unsafety issues with future users of the `String`, as the rest of
1376 /// the standard library assumes that `String`s are valid UTF-8.
1383 /// let mut s = String::from("hello");
1386 /// let vec = s.as_mut_vec();
1387 /// assert_eq!(&[104, 101, 108, 108, 111][..], &vec[..]);
1391 /// assert_eq!(s, "olleh");
1394 #[stable(feature = "rust1", since = "1.0.0")]
1395 pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1399 /// Returns the length of this `String`, in bytes, not [`char`]s or
1400 /// graphemes. In other words, it may not be what a human considers the
1401 /// length of the string.
1408 /// let a = String::from("foo");
1409 /// assert_eq!(a.len(), 3);
1411 /// let fancy_f = String::from("ƒoo");
1412 /// assert_eq!(fancy_f.len(), 4);
1413 /// assert_eq!(fancy_f.chars().count(), 3);
1416 #[stable(feature = "rust1", since = "1.0.0")]
1417 pub fn len(&self) -> usize {
1421 /// Returns `true` if this `String` has a length of zero, and `false` otherwise.
1428 /// let mut v = String::new();
1429 /// assert!(v.is_empty());
1432 /// assert!(!v.is_empty());
1435 #[stable(feature = "rust1", since = "1.0.0")]
1436 pub fn is_empty(&self) -> bool {
1440 /// Splits the string into two at the given index.
1442 /// Returns a newly allocated `String`. `self` contains bytes `[0, at)`, and
1443 /// the returned `String` contains bytes `[at, len)`. `at` must be on the
1444 /// boundary of a UTF-8 code point.
1446 /// Note that the capacity of `self` does not change.
1450 /// Panics if `at` is not on a `UTF-8` code point boundary, or if it is beyond the last
1451 /// code point of the string.
1457 /// let mut hello = String::from("Hello, World!");
1458 /// let world = hello.split_off(7);
1459 /// assert_eq!(hello, "Hello, ");
1460 /// assert_eq!(world, "World!");
1464 #[stable(feature = "string_split_off", since = "1.16.0")]
1465 #[must_use = "use `.truncate()` if you don't need the other half"]
1466 pub fn split_off(&mut self, at: usize) -> String {
1467 assert!(self.is_char_boundary(at));
1468 let other = self.vec.split_off(at);
1469 unsafe { String::from_utf8_unchecked(other) }
1472 /// Truncates this `String`, removing all contents.
1474 /// While this means the `String` will have a length of zero, it does not
1475 /// touch its capacity.
1482 /// let mut s = String::from("foo");
1486 /// assert!(s.is_empty());
1487 /// assert_eq!(0, s.len());
1488 /// assert_eq!(3, s.capacity());
1491 #[stable(feature = "rust1", since = "1.0.0")]
1492 pub fn clear(&mut self) {
1496 /// Creates a draining iterator that removes the specified range in the `String`
1497 /// and yields the removed `chars`.
1499 /// Note: The element range is removed even if the iterator is not
1500 /// consumed until the end.
1504 /// Panics if the starting point or end point do not lie on a [`char`]
1505 /// boundary, or if they're out of bounds.
1507 /// [`char`]: ../../std/primitive.char.html
1514 /// let mut s = String::from("α is alpha, β is beta");
1515 /// let beta_offset = s.find('β').unwrap_or(s.len());
1517 /// // Remove the range up until the β from the string
1518 /// let t: String = s.drain(..beta_offset).collect();
1519 /// assert_eq!(t, "α is alpha, ");
1520 /// assert_eq!(s, "β is beta");
1522 /// // A full range clears the string
1524 /// assert_eq!(s, "");
1526 #[stable(feature = "drain", since = "1.6.0")]
1527 pub fn drain<R>(&mut self, range: R) -> Drain<'_>
1529 R: RangeBounds<usize>,
1533 // The String version of Drain does not have the memory safety issues
1534 // of the vector version. The data is just plain bytes.
1535 // Because the range removal happens in Drop, if the Drain iterator is leaked,
1536 // the removal will not happen.
1537 let len = self.len();
1538 let start = match range.start_bound() {
1540 Excluded(&n) => n + 1,
1543 let end = match range.end_bound() {
1544 Included(&n) => n + 1,
1549 // Take out two simultaneous borrows. The &mut String won't be accessed
1550 // until iteration is over, in Drop.
1551 let self_ptr = self as *mut _;
1552 // slicing does the appropriate bounds checks
1553 let chars_iter = self[start..end].chars();
1555 Drain { start, end, iter: chars_iter, string: self_ptr }
1558 /// Removes the specified range in the string,
1559 /// and replaces it with the given string.
1560 /// The given string doesn't need to be the same length as the range.
1564 /// Panics if the starting point or end point do not lie on a [`char`]
1565 /// boundary, or if they're out of bounds.
1567 /// [`char`]: ../../std/primitive.char.html
1568 /// [`Vec::splice`]: ../../std/vec/struct.Vec.html#method.splice
1575 /// let mut s = String::from("α is alpha, β is beta");
1576 /// let beta_offset = s.find('β').unwrap_or(s.len());
1578 /// // Replace the range up until the β from the string
1579 /// s.replace_range(..beta_offset, "Α is capital alpha; ");
1580 /// assert_eq!(s, "Α is capital alpha; β is beta");
1582 #[stable(feature = "splice", since = "1.27.0")]
1583 pub fn replace_range<R>(&mut self, range: R, replace_with: &str)
1585 R: RangeBounds<usize>,
1589 // Replace_range does not have the memory safety issues of a vector Splice.
1590 // of the vector version. The data is just plain bytes.
1592 match range.start_bound() {
1593 Included(&n) => assert!(self.is_char_boundary(n)),
1594 Excluded(&n) => assert!(self.is_char_boundary(n + 1)),
1597 match range.end_bound() {
1598 Included(&n) => assert!(self.is_char_boundary(n + 1)),
1599 Excluded(&n) => assert!(self.is_char_boundary(n)),
1603 unsafe { self.as_mut_vec() }.splice(range, replace_with.bytes());
1606 /// Converts this `String` into a [`Box`]`<`[`str`]`>`.
1608 /// This will drop any excess capacity.
1610 /// [`Box`]: ../../std/boxed/struct.Box.html
1611 /// [`str`]: ../../std/primitive.str.html
1618 /// let s = String::from("hello");
1620 /// let b = s.into_boxed_str();
1622 #[stable(feature = "box_str", since = "1.4.0")]
1624 pub fn into_boxed_str(self) -> Box<str> {
1625 let slice = self.vec.into_boxed_slice();
1626 unsafe { from_boxed_utf8_unchecked(slice) }
1630 impl FromUtf8Error {
1631 /// Returns a slice of [`u8`]s bytes that were attempted to convert to a `String`.
1638 /// // some invalid bytes, in a vector
1639 /// let bytes = vec![0, 159];
1641 /// let value = String::from_utf8(bytes);
1643 /// assert_eq!(&[0, 159], value.unwrap_err().as_bytes());
1645 #[stable(feature = "from_utf8_error_as_bytes", since = "1.26.0")]
1646 pub fn as_bytes(&self) -> &[u8] {
1650 /// Returns the bytes that were attempted to convert to a `String`.
1652 /// This method is carefully constructed to avoid allocation. It will
1653 /// consume the error, moving out the bytes, so that a copy of the bytes
1654 /// does not need to be made.
1661 /// // some invalid bytes, in a vector
1662 /// let bytes = vec![0, 159];
1664 /// let value = String::from_utf8(bytes);
1666 /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
1668 #[stable(feature = "rust1", since = "1.0.0")]
1669 pub fn into_bytes(self) -> Vec<u8> {
1673 /// Fetch a `Utf8Error` to get more details about the conversion failure.
1675 /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
1676 /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
1677 /// an analogue to `FromUtf8Error`. See its documentation for more details
1680 /// [`Utf8Error`]: ../../std/str/struct.Utf8Error.html
1681 /// [`std::str`]: ../../std/str/index.html
1682 /// [`u8`]: ../../std/primitive.u8.html
1683 /// [`&str`]: ../../std/primitive.str.html
1690 /// // some invalid bytes, in a vector
1691 /// let bytes = vec![0, 159];
1693 /// let error = String::from_utf8(bytes).unwrap_err().utf8_error();
1695 /// // the first byte is invalid here
1696 /// assert_eq!(1, error.valid_up_to());
1698 #[stable(feature = "rust1", since = "1.0.0")]
1699 pub fn utf8_error(&self) -> Utf8Error {
1704 #[stable(feature = "rust1", since = "1.0.0")]
1705 impl fmt::Display for FromUtf8Error {
1706 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1707 fmt::Display::fmt(&self.error, f)
1711 #[stable(feature = "rust1", since = "1.0.0")]
1712 impl fmt::Display for FromUtf16Error {
1713 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1714 fmt::Display::fmt("invalid utf-16: lone surrogate found", f)
1718 #[stable(feature = "rust1", since = "1.0.0")]
1719 impl Clone for String {
1720 fn clone(&self) -> Self {
1721 String { vec: self.vec.clone() }
1724 fn clone_from(&mut self, source: &Self) {
1725 self.vec.clone_from(&source.vec);
1729 #[stable(feature = "rust1", since = "1.0.0")]
1730 impl FromIterator<char> for String {
1731 fn from_iter<I: IntoIterator<Item = char>>(iter: I) -> String {
1732 let mut buf = String::new();
1738 #[stable(feature = "string_from_iter_by_ref", since = "1.17.0")]
1739 impl<'a> FromIterator<&'a char> for String {
1740 fn from_iter<I: IntoIterator<Item = &'a char>>(iter: I) -> String {
1741 let mut buf = String::new();
1747 #[stable(feature = "rust1", since = "1.0.0")]
1748 impl<'a> FromIterator<&'a str> for String {
1749 fn from_iter<I: IntoIterator<Item = &'a str>>(iter: I) -> String {
1750 let mut buf = String::new();
1756 #[stable(feature = "extend_string", since = "1.4.0")]
1757 impl FromIterator<String> for String {
1758 fn from_iter<I: IntoIterator<Item = String>>(iter: I) -> String {
1759 let mut iterator = iter.into_iter();
1761 // Because we're iterating over `String`s, we can avoid at least
1762 // one allocation by getting the first string from the iterator
1763 // and appending to it all the subsequent strings.
1764 match iterator.next() {
1765 None => String::new(),
1767 buf.extend(iterator);
1774 #[stable(feature = "herd_cows", since = "1.19.0")]
1775 impl<'a> FromIterator<Cow<'a, str>> for String {
1776 fn from_iter<I: IntoIterator<Item = Cow<'a, str>>>(iter: I) -> String {
1777 let mut iterator = iter.into_iter();
1779 // Because we're iterating over CoWs, we can (potentially) avoid at least
1780 // one allocation by getting the first item and appending to it all the
1781 // subsequent items.
1782 match iterator.next() {
1783 None => String::new(),
1785 let mut buf = cow.into_owned();
1786 buf.extend(iterator);
1793 #[stable(feature = "rust1", since = "1.0.0")]
1794 impl Extend<char> for String {
1795 fn extend<I: IntoIterator<Item = char>>(&mut self, iter: I) {
1796 let iterator = iter.into_iter();
1797 let (lower_bound, _) = iterator.size_hint();
1798 self.reserve(lower_bound);
1799 iterator.for_each(move |c| self.push(c));
1803 #[stable(feature = "extend_ref", since = "1.2.0")]
1804 impl<'a> Extend<&'a char> for String {
1805 fn extend<I: IntoIterator<Item = &'a char>>(&mut self, iter: I) {
1806 self.extend(iter.into_iter().cloned());
1810 #[stable(feature = "rust1", since = "1.0.0")]
1811 impl<'a> Extend<&'a str> for String {
1812 fn extend<I: IntoIterator<Item = &'a str>>(&mut self, iter: I) {
1813 iter.into_iter().for_each(move |s| self.push_str(s));
1817 #[stable(feature = "extend_string", since = "1.4.0")]
1818 impl Extend<String> for String {
1819 fn extend<I: IntoIterator<Item = String>>(&mut self, iter: I) {
1820 iter.into_iter().for_each(move |s| self.push_str(&s));
1824 #[stable(feature = "herd_cows", since = "1.19.0")]
1825 impl<'a> Extend<Cow<'a, str>> for String {
1826 fn extend<I: IntoIterator<Item = Cow<'a, str>>>(&mut self, iter: I) {
1827 iter.into_iter().for_each(move |s| self.push_str(&s));
1831 /// A convenience impl that delegates to the impl for `&str`
1833 feature = "pattern",
1834 reason = "API not fully fleshed out and ready to be stabilized",
1837 impl<'a, 'b> Pattern<'a> for &'b String {
1838 type Searcher = <&'b str as Pattern<'a>>::Searcher;
1840 fn into_searcher(self, haystack: &'a str) -> <&'b str as Pattern<'a>>::Searcher {
1841 self[..].into_searcher(haystack)
1845 fn is_contained_in(self, haystack: &'a str) -> bool {
1846 self[..].is_contained_in(haystack)
1850 fn is_prefix_of(self, haystack: &'a str) -> bool {
1851 self[..].is_prefix_of(haystack)
1855 #[stable(feature = "rust1", since = "1.0.0")]
1856 impl PartialEq for String {
1858 fn eq(&self, other: &String) -> bool {
1859 PartialEq::eq(&self[..], &other[..])
1862 fn ne(&self, other: &String) -> bool {
1863 PartialEq::ne(&self[..], &other[..])
1867 macro_rules! impl_eq {
1868 ($lhs:ty, $rhs: ty) => {
1869 #[stable(feature = "rust1", since = "1.0.0")]
1870 #[allow(unused_lifetimes)]
1871 impl<'a, 'b> PartialEq<$rhs> for $lhs {
1873 fn eq(&self, other: &$rhs) -> bool {
1874 PartialEq::eq(&self[..], &other[..])
1877 fn ne(&self, other: &$rhs) -> bool {
1878 PartialEq::ne(&self[..], &other[..])
1882 #[stable(feature = "rust1", since = "1.0.0")]
1883 #[allow(unused_lifetimes)]
1884 impl<'a, 'b> PartialEq<$lhs> for $rhs {
1886 fn eq(&self, other: &$lhs) -> bool {
1887 PartialEq::eq(&self[..], &other[..])
1890 fn ne(&self, other: &$lhs) -> bool {
1891 PartialEq::ne(&self[..], &other[..])
1897 impl_eq! { String, str }
1898 impl_eq! { String, &'a str }
1899 impl_eq! { Cow<'a, str>, str }
1900 impl_eq! { Cow<'a, str>, &'b str }
1901 impl_eq! { Cow<'a, str>, String }
1903 #[stable(feature = "rust1", since = "1.0.0")]
1904 impl Default for String {
1905 /// Creates an empty `String`.
1907 fn default() -> String {
1912 #[stable(feature = "rust1", since = "1.0.0")]
1913 impl fmt::Display for String {
1915 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1916 fmt::Display::fmt(&**self, f)
1920 #[stable(feature = "rust1", since = "1.0.0")]
1921 impl fmt::Debug for String {
1923 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1924 fmt::Debug::fmt(&**self, f)
1928 #[stable(feature = "rust1", since = "1.0.0")]
1929 impl hash::Hash for String {
1931 fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
1932 (**self).hash(hasher)
1936 /// Implements the `+` operator for concatenating two strings.
1938 /// This consumes the `String` on the left-hand side and re-uses its buffer (growing it if
1939 /// necessary). This is done to avoid allocating a new `String` and copying the entire contents on
1940 /// every operation, which would lead to `O(n^2)` running time when building an `n`-byte string by
1941 /// repeated concatenation.
1943 /// The string on the right-hand side is only borrowed; its contents are copied into the returned
1948 /// Concatenating two `String`s takes the first by value and borrows the second:
1951 /// let a = String::from("hello");
1952 /// let b = String::from(" world");
1954 /// // `a` is moved and can no longer be used here.
1957 /// If you want to keep using the first `String`, you can clone it and append to the clone instead:
1960 /// let a = String::from("hello");
1961 /// let b = String::from(" world");
1962 /// let c = a.clone() + &b;
1963 /// // `a` is still valid here.
1966 /// Concatenating `&str` slices can be done by converting the first to a `String`:
1969 /// let a = "hello";
1970 /// let b = " world";
1971 /// let c = a.to_string() + b;
1973 #[stable(feature = "rust1", since = "1.0.0")]
1974 impl Add<&str> for String {
1975 type Output = String;
1978 fn add(mut self, other: &str) -> String {
1979 self.push_str(other);
1984 /// Implements the `+=` operator for appending to a `String`.
1986 /// This has the same behavior as the [`push_str`][String::push_str] method.
1987 #[stable(feature = "stringaddassign", since = "1.12.0")]
1988 impl AddAssign<&str> for String {
1990 fn add_assign(&mut self, other: &str) {
1991 self.push_str(other);
1995 #[stable(feature = "rust1", since = "1.0.0")]
1996 impl ops::Index<ops::Range<usize>> for String {
2000 fn index(&self, index: ops::Range<usize>) -> &str {
2004 #[stable(feature = "rust1", since = "1.0.0")]
2005 impl ops::Index<ops::RangeTo<usize>> for String {
2009 fn index(&self, index: ops::RangeTo<usize>) -> &str {
2013 #[stable(feature = "rust1", since = "1.0.0")]
2014 impl ops::Index<ops::RangeFrom<usize>> for String {
2018 fn index(&self, index: ops::RangeFrom<usize>) -> &str {
2022 #[stable(feature = "rust1", since = "1.0.0")]
2023 impl ops::Index<ops::RangeFull> for String {
2027 fn index(&self, _index: ops::RangeFull) -> &str {
2028 unsafe { str::from_utf8_unchecked(&self.vec) }
2031 #[stable(feature = "inclusive_range", since = "1.26.0")]
2032 impl ops::Index<ops::RangeInclusive<usize>> for String {
2036 fn index(&self, index: ops::RangeInclusive<usize>) -> &str {
2037 Index::index(&**self, index)
2040 #[stable(feature = "inclusive_range", since = "1.26.0")]
2041 impl ops::Index<ops::RangeToInclusive<usize>> for String {
2045 fn index(&self, index: ops::RangeToInclusive<usize>) -> &str {
2046 Index::index(&**self, index)
2050 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2051 impl ops::IndexMut<ops::Range<usize>> for String {
2053 fn index_mut(&mut self, index: ops::Range<usize>) -> &mut str {
2054 &mut self[..][index]
2057 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2058 impl ops::IndexMut<ops::RangeTo<usize>> for String {
2060 fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut str {
2061 &mut self[..][index]
2064 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2065 impl ops::IndexMut<ops::RangeFrom<usize>> for String {
2067 fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut str {
2068 &mut self[..][index]
2071 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2072 impl ops::IndexMut<ops::RangeFull> for String {
2074 fn index_mut(&mut self, _index: ops::RangeFull) -> &mut str {
2075 unsafe { str::from_utf8_unchecked_mut(&mut *self.vec) }
2078 #[stable(feature = "inclusive_range", since = "1.26.0")]
2079 impl ops::IndexMut<ops::RangeInclusive<usize>> for String {
2081 fn index_mut(&mut self, index: ops::RangeInclusive<usize>) -> &mut str {
2082 IndexMut::index_mut(&mut **self, index)
2085 #[stable(feature = "inclusive_range", since = "1.26.0")]
2086 impl ops::IndexMut<ops::RangeToInclusive<usize>> for String {
2088 fn index_mut(&mut self, index: ops::RangeToInclusive<usize>) -> &mut str {
2089 IndexMut::index_mut(&mut **self, index)
2093 #[stable(feature = "rust1", since = "1.0.0")]
2094 impl ops::Deref for String {
2098 fn deref(&self) -> &str {
2099 unsafe { str::from_utf8_unchecked(&self.vec) }
2103 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2104 impl ops::DerefMut for String {
2106 fn deref_mut(&mut self) -> &mut str {
2107 unsafe { str::from_utf8_unchecked_mut(&mut *self.vec) }
2111 /// A type alias for [`Infallible`].
2113 /// This alias exists for backwards compatibility, and may be eventually deprecated.
2115 /// [`Infallible`]: ../../core/convert/enum.Infallible.html
2116 #[stable(feature = "str_parse_error", since = "1.5.0")]
2117 pub type ParseError = core::convert::Infallible;
2119 #[stable(feature = "rust1", since = "1.0.0")]
2120 impl FromStr for String {
2121 type Err = core::convert::Infallible;
2123 fn from_str(s: &str) -> Result<String, Self::Err> {
2128 /// A trait for converting a value to a `String`.
2130 /// This trait is automatically implemented for any type which implements the
2131 /// [`Display`] trait. As such, `ToString` shouldn't be implemented directly:
2132 /// [`Display`] should be implemented instead, and you get the `ToString`
2133 /// implementation for free.
2135 /// [`Display`]: ../../std/fmt/trait.Display.html
2136 #[stable(feature = "rust1", since = "1.0.0")]
2137 pub trait ToString {
2138 /// Converts the given value to a `String`.
2146 /// let five = String::from("5");
2148 /// assert_eq!(five, i.to_string());
2150 #[rustc_conversion_suggestion]
2151 #[stable(feature = "rust1", since = "1.0.0")]
2152 fn to_string(&self) -> String;
2157 /// In this implementation, the `to_string` method panics
2158 /// if the `Display` implementation returns an error.
2159 /// This indicates an incorrect `Display` implementation
2160 /// since `fmt::Write for String` never returns an error itself.
2161 #[stable(feature = "rust1", since = "1.0.0")]
2162 impl<T: fmt::Display + ?Sized> ToString for T {
2164 default fn to_string(&self) -> String {
2166 let mut buf = String::new();
2167 buf.write_fmt(format_args!("{}", self))
2168 .expect("a Display implementation returned an error unexpectedly");
2169 buf.shrink_to_fit();
2174 #[stable(feature = "str_to_string_specialization", since = "1.9.0")]
2175 impl ToString for str {
2177 fn to_string(&self) -> String {
2182 #[stable(feature = "cow_str_to_string_specialization", since = "1.17.0")]
2183 impl ToString for Cow<'_, str> {
2185 fn to_string(&self) -> String {
2190 #[stable(feature = "string_to_string_specialization", since = "1.17.0")]
2191 impl ToString for String {
2193 fn to_string(&self) -> String {
2198 #[stable(feature = "rust1", since = "1.0.0")]
2199 impl AsRef<str> for String {
2201 fn as_ref(&self) -> &str {
2206 #[stable(feature = "string_as_mut", since = "1.43.0")]
2207 impl AsMut<str> for String {
2209 fn as_mut(&mut self) -> &mut str {
2214 #[stable(feature = "rust1", since = "1.0.0")]
2215 impl AsRef<[u8]> for String {
2217 fn as_ref(&self) -> &[u8] {
2222 #[stable(feature = "rust1", since = "1.0.0")]
2223 impl From<&str> for String {
2225 fn from(s: &str) -> String {
2230 #[stable(feature = "from_mut_str_for_string", since = "1.44.0")]
2231 impl From<&mut str> for String {
2232 /// Converts a `&mut str` into a `String`.
2234 /// The result is allocated on the heap.
2236 fn from(s: &mut str) -> String {
2241 #[stable(feature = "from_ref_string", since = "1.35.0")]
2242 impl From<&String> for String {
2244 fn from(s: &String) -> String {
2249 // note: test pulls in libstd, which causes errors here
2251 #[stable(feature = "string_from_box", since = "1.18.0")]
2252 impl From<Box<str>> for String {
2253 /// Converts the given boxed `str` slice to a `String`.
2254 /// It is notable that the `str` slice is owned.
2261 /// let s1: String = String::from("hello world");
2262 /// let s2: Box<str> = s1.into_boxed_str();
2263 /// let s3: String = String::from(s2);
2265 /// assert_eq!("hello world", s3)
2267 fn from(s: Box<str>) -> String {
2272 #[stable(feature = "box_from_str", since = "1.20.0")]
2273 impl From<String> for Box<str> {
2274 /// Converts the given `String` to a boxed `str` slice that is owned.
2281 /// let s1: String = String::from("hello world");
2282 /// let s2: Box<str> = Box::from(s1);
2283 /// let s3: String = String::from(s2);
2285 /// assert_eq!("hello world", s3)
2287 fn from(s: String) -> Box<str> {
2292 #[stable(feature = "string_from_cow_str", since = "1.14.0")]
2293 impl<'a> From<Cow<'a, str>> for String {
2294 fn from(s: Cow<'a, str>) -> String {
2299 #[stable(feature = "rust1", since = "1.0.0")]
2300 impl<'a> From<&'a str> for Cow<'a, str> {
2302 fn from(s: &'a str) -> Cow<'a, str> {
2307 #[stable(feature = "rust1", since = "1.0.0")]
2308 impl<'a> From<String> for Cow<'a, str> {
2310 fn from(s: String) -> Cow<'a, str> {
2315 #[stable(feature = "cow_from_string_ref", since = "1.28.0")]
2316 impl<'a> From<&'a String> for Cow<'a, str> {
2318 fn from(s: &'a String) -> Cow<'a, str> {
2319 Cow::Borrowed(s.as_str())
2323 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2324 impl<'a> FromIterator<char> for Cow<'a, str> {
2325 fn from_iter<I: IntoIterator<Item = char>>(it: I) -> Cow<'a, str> {
2326 Cow::Owned(FromIterator::from_iter(it))
2330 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2331 impl<'a, 'b> FromIterator<&'b str> for Cow<'a, str> {
2332 fn from_iter<I: IntoIterator<Item = &'b str>>(it: I) -> Cow<'a, str> {
2333 Cow::Owned(FromIterator::from_iter(it))
2337 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2338 impl<'a> FromIterator<String> for Cow<'a, str> {
2339 fn from_iter<I: IntoIterator<Item = String>>(it: I) -> Cow<'a, str> {
2340 Cow::Owned(FromIterator::from_iter(it))
2344 #[stable(feature = "from_string_for_vec_u8", since = "1.14.0")]
2345 impl From<String> for Vec<u8> {
2346 /// Converts the given `String` to a vector `Vec` that holds values of type `u8`.
2353 /// let s1 = String::from("hello world");
2354 /// let v1 = Vec::from(s1);
2357 /// println!("{}", b);
2360 fn from(string: String) -> Vec<u8> {
2365 #[stable(feature = "rust1", since = "1.0.0")]
2366 impl fmt::Write for String {
2368 fn write_str(&mut self, s: &str) -> fmt::Result {
2374 fn write_char(&mut self, c: char) -> fmt::Result {
2380 /// A draining iterator for `String`.
2382 /// This struct is created by the [`drain`] method on [`String`]. See its
2383 /// documentation for more.
2385 /// [`drain`]: struct.String.html#method.drain
2386 /// [`String`]: struct.String.html
2387 #[stable(feature = "drain", since = "1.6.0")]
2388 pub struct Drain<'a> {
2389 /// Will be used as &'a mut String in the destructor
2390 string: *mut String,
2391 /// Start of part to remove
2393 /// End of part to remove
2395 /// Current remaining range to remove
2399 #[stable(feature = "collection_debug", since = "1.17.0")]
2400 impl fmt::Debug for Drain<'_> {
2401 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2402 f.pad("Drain { .. }")
2406 #[stable(feature = "drain", since = "1.6.0")]
2407 unsafe impl Sync for Drain<'_> {}
2408 #[stable(feature = "drain", since = "1.6.0")]
2409 unsafe impl Send for Drain<'_> {}
2411 #[stable(feature = "drain", since = "1.6.0")]
2412 impl Drop for Drain<'_> {
2413 fn drop(&mut self) {
2415 // Use Vec::drain. "Reaffirm" the bounds checks to avoid
2416 // panic code being inserted again.
2417 let self_vec = (*self.string).as_mut_vec();
2418 if self.start <= self.end && self.end <= self_vec.len() {
2419 self_vec.drain(self.start..self.end);
2425 #[stable(feature = "drain", since = "1.6.0")]
2426 impl Iterator for Drain<'_> {
2430 fn next(&mut self) -> Option<char> {
2434 fn size_hint(&self) -> (usize, Option<usize>) {
2435 self.iter.size_hint()
2439 fn last(mut self) -> Option<char> {
2444 #[stable(feature = "drain", since = "1.6.0")]
2445 impl DoubleEndedIterator for Drain<'_> {
2447 fn next_back(&mut self) -> Option<char> {
2448 self.iter.next_back()
2452 #[stable(feature = "fused", since = "1.26.0")]
2453 impl FusedIterator for Drain<'_> {}