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")]
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 vector 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::from_utf8`]: ../../std/str/fn.from_utf8.html
486 /// [`into_bytes`]: struct.String.html#method.into_bytes
487 /// [`FromUtf8Error`]: struct.FromUtf8Error.html
488 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
490 #[stable(feature = "rust1", since = "1.0.0")]
491 pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error> {
492 match str::from_utf8(&vec) {
493 Ok(..) => Ok(String { vec }),
494 Err(e) => Err(FromUtf8Error { bytes: vec, error: e }),
498 /// Converts a slice of bytes to a string, including invalid characters.
500 /// Strings are made of bytes ([`u8`]), and a slice of bytes
501 /// ([`&[u8]`][byteslice]) is made of bytes, so this function converts
502 /// between the two. Not all byte slices are valid strings, however: strings
503 /// are required to be valid UTF-8. During this conversion,
504 /// `from_utf8_lossy()` will replace any invalid UTF-8 sequences with
505 /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD], which looks like this: �
507 /// [`u8`]: ../../std/primitive.u8.html
508 /// [byteslice]: ../../std/primitive.slice.html
509 /// [U+FFFD]: ../char/constant.REPLACEMENT_CHARACTER.html
511 /// If you are sure that the byte slice is valid UTF-8, and you don't want
512 /// to incur the overhead of the conversion, there is an unsafe version
513 /// of this function, [`from_utf8_unchecked`], which has the same behavior
514 /// but skips the checks.
516 /// [`from_utf8_unchecked`]: struct.String.html#method.from_utf8_unchecked
518 /// This function returns a [`Cow<'a, str>`]. If our byte slice is invalid
519 /// UTF-8, then we need to insert the replacement characters, which will
520 /// change the size of the string, and hence, require a `String`. But if
521 /// it's already valid UTF-8, we don't need a new allocation. This return
522 /// type allows us to handle both cases.
524 /// [`Cow<'a, str>`]: ../../std/borrow/enum.Cow.html
531 /// // some bytes, in a vector
532 /// let sparkle_heart = vec![240, 159, 146, 150];
534 /// let sparkle_heart = String::from_utf8_lossy(&sparkle_heart);
536 /// assert_eq!("💖", sparkle_heart);
542 /// // some invalid bytes
543 /// let input = b"Hello \xF0\x90\x80World";
544 /// let output = String::from_utf8_lossy(input);
546 /// assert_eq!("Hello �World", output);
548 #[stable(feature = "rust1", since = "1.0.0")]
549 pub fn from_utf8_lossy(v: &[u8]) -> Cow<'_, str> {
550 let mut iter = lossy::Utf8Lossy::from_bytes(v).chunks();
552 let (first_valid, first_broken) = if let Some(chunk) = iter.next() {
553 let lossy::Utf8LossyChunk { valid, broken } = chunk;
554 if valid.len() == v.len() {
555 debug_assert!(broken.is_empty());
556 return Cow::Borrowed(valid);
560 return Cow::Borrowed("");
563 const REPLACEMENT: &str = "\u{FFFD}";
565 let mut res = String::with_capacity(v.len());
566 res.push_str(first_valid);
567 if !first_broken.is_empty() {
568 res.push_str(REPLACEMENT);
571 for lossy::Utf8LossyChunk { valid, broken } in iter {
573 if !broken.is_empty() {
574 res.push_str(REPLACEMENT);
581 /// Decode a UTF-16 encoded vector `v` into a `String`, returning [`Err`]
582 /// if `v` contains any invalid data.
584 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
592 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
593 /// 0x0073, 0x0069, 0x0063];
594 /// assert_eq!(String::from("𝄞music"),
595 /// String::from_utf16(v).unwrap());
597 /// // 𝄞mu<invalid>ic
598 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
599 /// 0xD800, 0x0069, 0x0063];
600 /// assert!(String::from_utf16(v).is_err());
602 #[stable(feature = "rust1", since = "1.0.0")]
603 pub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error> {
604 // This isn't done via collect::<Result<_, _>>() for performance reasons.
605 // FIXME: the function can be simplified again when #48994 is closed.
606 let mut ret = String::with_capacity(v.len());
607 for c in decode_utf16(v.iter().cloned()) {
611 return Err(FromUtf16Error(()));
617 /// Decode a UTF-16 encoded slice `v` into a `String`, replacing
618 /// invalid data with [the replacement character (`U+FFFD`)][U+FFFD].
620 /// Unlike [`from_utf8_lossy`] which returns a [`Cow<'a, str>`],
621 /// `from_utf16_lossy` returns a `String` since the UTF-16 to UTF-8
622 /// conversion requires a memory allocation.
624 /// [`from_utf8_lossy`]: #method.from_utf8_lossy
625 /// [`Cow<'a, str>`]: ../borrow/enum.Cow.html
626 /// [U+FFFD]: ../char/constant.REPLACEMENT_CHARACTER.html
633 /// // 𝄞mus<invalid>ic<invalid>
634 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
635 /// 0x0073, 0xDD1E, 0x0069, 0x0063,
638 /// assert_eq!(String::from("𝄞mus\u{FFFD}ic\u{FFFD}"),
639 /// String::from_utf16_lossy(v));
642 #[stable(feature = "rust1", since = "1.0.0")]
643 pub fn from_utf16_lossy(v: &[u16]) -> String {
644 decode_utf16(v.iter().cloned()).map(|r| r.unwrap_or(REPLACEMENT_CHARACTER)).collect()
647 /// Decomposes a `String` into its raw components.
649 /// Returns the raw pointer to the underlying data, the length of
650 /// the string (in bytes), and the allocated capacity of the data
651 /// (in bytes). These are the same arguments in the same order as
652 /// the arguments to [`from_raw_parts`].
654 /// After calling this function, the caller is responsible for the
655 /// memory previously managed by the `String`. The only way to do
656 /// this is to convert the raw pointer, length, and capacity back
657 /// into a `String` with the [`from_raw_parts`] function, allowing
658 /// the destructor to perform the cleanup.
660 /// [`from_raw_parts`]: #method.from_raw_parts
665 /// #![feature(vec_into_raw_parts)]
666 /// let s = String::from("hello");
668 /// let (ptr, len, cap) = s.into_raw_parts();
670 /// let rebuilt = unsafe { String::from_raw_parts(ptr, len, cap) };
671 /// assert_eq!(rebuilt, "hello");
673 #[unstable(feature = "vec_into_raw_parts", reason = "new API", issue = "65816")]
674 pub fn into_raw_parts(self) -> (*mut u8, usize, usize) {
675 self.vec.into_raw_parts()
678 /// Creates a new `String` from a length, capacity, and pointer.
682 /// This is highly unsafe, due to the number of invariants that aren't
685 /// * The memory at `ptr` needs to have been previously allocated by the
686 /// same allocator the standard library uses, with a required alignment of exactly 1.
687 /// * `length` needs to be less than or equal to `capacity`.
688 /// * `capacity` needs to be the correct value.
690 /// Violating these may cause problems like corrupting the allocator's
691 /// internal data structures.
693 /// The ownership of `ptr` is effectively transferred to the
694 /// `String` which may then deallocate, reallocate or change the
695 /// contents of memory pointed to by the pointer at will. Ensure
696 /// that nothing else uses the pointer after calling this
707 /// let s = String::from("hello");
709 // FIXME Update this when vec_into_raw_parts is stabilized
710 /// // Prevent automatically dropping the String's data
711 /// let mut s = mem::ManuallyDrop::new(s);
713 /// let ptr = s.as_mut_ptr();
714 /// let len = s.len();
715 /// let capacity = s.capacity();
717 /// let s = String::from_raw_parts(ptr, len, capacity);
719 /// assert_eq!(String::from("hello"), s);
723 #[stable(feature = "rust1", since = "1.0.0")]
724 pub unsafe fn from_raw_parts(buf: *mut u8, length: usize, capacity: usize) -> String {
725 String { vec: Vec::from_raw_parts(buf, length, capacity) }
728 /// Converts a vector of bytes to a `String` without checking that the
729 /// string contains valid UTF-8.
731 /// See the safe version, [`from_utf8`], for more details.
733 /// [`from_utf8`]: struct.String.html#method.from_utf8
737 /// This function is unsafe because it does not check that the bytes passed
738 /// to it are valid UTF-8. If this constraint is violated, it may cause
739 /// memory unsafety issues with future users of the `String`, as the rest of
740 /// the standard library assumes that `String`s are valid UTF-8.
747 /// // some bytes, in a vector
748 /// let sparkle_heart = vec![240, 159, 146, 150];
750 /// let sparkle_heart = unsafe {
751 /// String::from_utf8_unchecked(sparkle_heart)
754 /// assert_eq!("💖", sparkle_heart);
757 #[stable(feature = "rust1", since = "1.0.0")]
758 pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String {
759 String { vec: bytes }
762 /// Converts a `String` into a byte vector.
764 /// This consumes the `String`, so we do not need to copy its contents.
771 /// let s = String::from("hello");
772 /// let bytes = s.into_bytes();
774 /// assert_eq!(&[104, 101, 108, 108, 111][..], &bytes[..]);
777 #[stable(feature = "rust1", since = "1.0.0")]
778 pub fn into_bytes(self) -> Vec<u8> {
782 /// Extracts a string slice containing the entire `String`.
789 /// let s = String::from("foo");
791 /// assert_eq!("foo", s.as_str());
794 #[stable(feature = "string_as_str", since = "1.7.0")]
795 pub fn as_str(&self) -> &str {
799 /// Converts a `String` into a mutable string slice.
806 /// let mut s = String::from("foobar");
807 /// let s_mut_str = s.as_mut_str();
809 /// s_mut_str.make_ascii_uppercase();
811 /// assert_eq!("FOOBAR", s_mut_str);
814 #[stable(feature = "string_as_str", since = "1.7.0")]
815 pub fn as_mut_str(&mut self) -> &mut str {
819 /// Appends a given string slice onto the end of this `String`.
826 /// let mut s = String::from("foo");
828 /// s.push_str("bar");
830 /// assert_eq!("foobar", s);
833 #[stable(feature = "rust1", since = "1.0.0")]
834 pub fn push_str(&mut self, string: &str) {
835 self.vec.extend_from_slice(string.as_bytes())
838 /// Returns this `String`'s capacity, in bytes.
845 /// let s = String::with_capacity(10);
847 /// assert!(s.capacity() >= 10);
850 #[stable(feature = "rust1", since = "1.0.0")]
851 pub fn capacity(&self) -> usize {
855 /// Ensures that this `String`'s capacity is at least `additional` bytes
856 /// larger than its length.
858 /// The capacity may be increased by more than `additional` bytes if it
859 /// chooses, to prevent frequent reallocations.
861 /// If you do not want this "at least" behavior, see the [`reserve_exact`]
866 /// Panics if the new capacity overflows [`usize`].
868 /// [`reserve_exact`]: struct.String.html#method.reserve_exact
869 /// [`usize`]: ../../std/primitive.usize.html
876 /// let mut s = String::new();
880 /// assert!(s.capacity() >= 10);
883 /// This may not actually increase the capacity:
886 /// let mut s = String::with_capacity(10);
890 /// // s now has a length of 2 and a capacity of 10
891 /// assert_eq!(2, s.len());
892 /// assert_eq!(10, s.capacity());
894 /// // Since we already have an extra 8 capacity, calling this...
897 /// // ... doesn't actually increase.
898 /// assert_eq!(10, s.capacity());
901 #[stable(feature = "rust1", since = "1.0.0")]
902 pub fn reserve(&mut self, additional: usize) {
903 self.vec.reserve(additional)
906 /// Ensures that this `String`'s capacity is `additional` bytes
907 /// larger than its length.
909 /// Consider using the [`reserve`] method unless you absolutely know
910 /// better than the allocator.
912 /// [`reserve`]: #method.reserve
916 /// Panics if the new capacity overflows `usize`.
923 /// let mut s = String::new();
925 /// s.reserve_exact(10);
927 /// assert!(s.capacity() >= 10);
930 /// This may not actually increase the capacity:
933 /// let mut s = String::with_capacity(10);
937 /// // s now has a length of 2 and a capacity of 10
938 /// assert_eq!(2, s.len());
939 /// assert_eq!(10, s.capacity());
941 /// // Since we already have an extra 8 capacity, calling this...
942 /// s.reserve_exact(8);
944 /// // ... doesn't actually increase.
945 /// assert_eq!(10, s.capacity());
948 #[stable(feature = "rust1", since = "1.0.0")]
949 pub fn reserve_exact(&mut self, additional: usize) {
950 self.vec.reserve_exact(additional)
953 /// Tries to reserve capacity for at least `additional` more elements to be inserted
954 /// in the given `String`. The collection may reserve more space to avoid
955 /// frequent reallocations. After calling `reserve`, capacity will be
956 /// greater than or equal to `self.len() + additional`. Does nothing if
957 /// capacity is already sufficient.
961 /// If the capacity overflows, or the allocator reports a failure, then an error
967 /// #![feature(try_reserve)]
968 /// use std::collections::TryReserveError;
970 /// fn process_data(data: &str) -> Result<String, TryReserveError> {
971 /// let mut output = String::new();
973 /// // Pre-reserve the memory, exiting if we can't
974 /// output.try_reserve(data.len())?;
976 /// // Now we know this can't OOM in the middle of our complex work
977 /// output.push_str(data);
981 /// # process_data("rust").expect("why is the test harness OOMing on 4 bytes?");
983 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
984 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
985 self.vec.try_reserve(additional)
988 /// Tries to reserves the minimum capacity for exactly `additional` more elements to
989 /// be inserted in the given `String`. After calling `reserve_exact`,
990 /// capacity will be greater than or equal to `self.len() + additional`.
991 /// Does nothing if the capacity is already sufficient.
993 /// Note that the allocator may give the collection more space than it
994 /// requests. Therefore, capacity can not be relied upon to be precisely
995 /// minimal. Prefer `reserve` if future insertions are expected.
999 /// If the capacity overflows, or the allocator reports a failure, then an error
1005 /// #![feature(try_reserve)]
1006 /// use std::collections::TryReserveError;
1008 /// fn process_data(data: &str) -> Result<String, TryReserveError> {
1009 /// let mut output = String::new();
1011 /// // Pre-reserve the memory, exiting if we can't
1012 /// output.try_reserve(data.len())?;
1014 /// // Now we know this can't OOM in the middle of our complex work
1015 /// output.push_str(data);
1019 /// # process_data("rust").expect("why is the test harness OOMing on 4 bytes?");
1021 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
1022 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
1023 self.vec.try_reserve_exact(additional)
1026 /// Shrinks the capacity of this `String` to match its length.
1033 /// let mut s = String::from("foo");
1036 /// assert!(s.capacity() >= 100);
1038 /// s.shrink_to_fit();
1039 /// assert_eq!(3, s.capacity());
1042 #[stable(feature = "rust1", since = "1.0.0")]
1043 pub fn shrink_to_fit(&mut self) {
1044 self.vec.shrink_to_fit()
1047 /// Shrinks the capacity of this `String` with a lower bound.
1049 /// The capacity will remain at least as large as both the length
1050 /// and the supplied value.
1052 /// Panics if the current capacity is smaller than the supplied
1053 /// minimum capacity.
1058 /// #![feature(shrink_to)]
1059 /// let mut s = String::from("foo");
1062 /// assert!(s.capacity() >= 100);
1064 /// s.shrink_to(10);
1065 /// assert!(s.capacity() >= 10);
1067 /// assert!(s.capacity() >= 3);
1070 #[unstable(feature = "shrink_to", reason = "new API", issue = "56431")]
1071 pub fn shrink_to(&mut self, min_capacity: usize) {
1072 self.vec.shrink_to(min_capacity)
1075 /// Appends the given [`char`] to the end of this `String`.
1077 /// [`char`]: ../../std/primitive.char.html
1084 /// let mut s = String::from("abc");
1090 /// assert_eq!("abc123", s);
1093 #[stable(feature = "rust1", since = "1.0.0")]
1094 pub fn push(&mut self, ch: char) {
1095 match ch.len_utf8() {
1096 1 => self.vec.push(ch as u8),
1097 _ => self.vec.extend_from_slice(ch.encode_utf8(&mut [0; 4]).as_bytes()),
1101 /// Returns a byte slice of this `String`'s contents.
1103 /// The inverse of this method is [`from_utf8`].
1105 /// [`from_utf8`]: #method.from_utf8
1112 /// let s = String::from("hello");
1114 /// assert_eq!(&[104, 101, 108, 108, 111], s.as_bytes());
1117 #[stable(feature = "rust1", since = "1.0.0")]
1118 pub fn as_bytes(&self) -> &[u8] {
1122 /// Shortens this `String` to the specified length.
1124 /// If `new_len` is greater than the string's current length, this has no
1127 /// Note that this method has no effect on the allocated capacity
1132 /// Panics if `new_len` does not lie on a [`char`] boundary.
1134 /// [`char`]: ../../std/primitive.char.html
1141 /// let mut s = String::from("hello");
1145 /// assert_eq!("he", s);
1148 #[stable(feature = "rust1", since = "1.0.0")]
1149 pub fn truncate(&mut self, new_len: usize) {
1150 if new_len <= self.len() {
1151 assert!(self.is_char_boundary(new_len));
1152 self.vec.truncate(new_len)
1156 /// Removes the last character from the string buffer and returns it.
1158 /// Returns [`None`] if this `String` is empty.
1160 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1167 /// let mut s = String::from("foo");
1169 /// assert_eq!(s.pop(), Some('o'));
1170 /// assert_eq!(s.pop(), Some('o'));
1171 /// assert_eq!(s.pop(), Some('f'));
1173 /// assert_eq!(s.pop(), None);
1176 #[stable(feature = "rust1", since = "1.0.0")]
1177 pub fn pop(&mut self) -> Option<char> {
1178 let ch = self.chars().rev().next()?;
1179 let newlen = self.len() - ch.len_utf8();
1181 self.vec.set_len(newlen);
1186 /// Removes a [`char`] from this `String` at a byte position and returns it.
1188 /// This is an `O(n)` operation, as it requires copying every element in the
1193 /// Panics if `idx` is larger than or equal to the `String`'s length,
1194 /// or if it does not lie on a [`char`] boundary.
1196 /// [`char`]: ../../std/primitive.char.html
1203 /// let mut s = String::from("foo");
1205 /// assert_eq!(s.remove(0), 'f');
1206 /// assert_eq!(s.remove(1), 'o');
1207 /// assert_eq!(s.remove(0), 'o');
1210 #[stable(feature = "rust1", since = "1.0.0")]
1211 pub fn remove(&mut self, idx: usize) -> char {
1212 let ch = match self[idx..].chars().next() {
1214 None => panic!("cannot remove a char from the end of a string"),
1217 let next = idx + ch.len_utf8();
1218 let len = self.len();
1220 ptr::copy(self.vec.as_ptr().add(next), self.vec.as_mut_ptr().add(idx), len - next);
1221 self.vec.set_len(len - (next - idx));
1226 /// Retains only the characters specified by the predicate.
1228 /// In other words, remove all characters `c` such that `f(c)` returns `false`.
1229 /// This method operates in place, visiting each character exactly once in the
1230 /// original order, and preserves the order of the retained characters.
1235 /// let mut s = String::from("f_o_ob_ar");
1237 /// s.retain(|c| c != '_');
1239 /// assert_eq!(s, "foobar");
1242 /// The exact order may be useful for tracking external state, like an index.
1245 /// let mut s = String::from("abcde");
1246 /// let keep = [false, true, true, false, true];
1248 /// s.retain(|_| (keep[i], i += 1).0);
1249 /// assert_eq!(s, "bce");
1252 #[stable(feature = "string_retain", since = "1.26.0")]
1253 pub fn retain<F>(&mut self, mut f: F)
1255 F: FnMut(char) -> bool,
1257 let len = self.len();
1258 let mut del_bytes = 0;
1262 let ch = unsafe { self.get_unchecked(idx..len).chars().next().unwrap() };
1263 let ch_len = ch.len_utf8();
1266 del_bytes += ch_len;
1267 } else if del_bytes > 0 {
1270 self.vec.as_ptr().add(idx),
1271 self.vec.as_mut_ptr().add(idx - del_bytes),
1277 // Point idx to the next char
1283 self.vec.set_len(len - del_bytes);
1288 /// Inserts a character into this `String` at a byte position.
1290 /// This is an `O(n)` operation as it requires copying every element in the
1295 /// Panics if `idx` is larger than the `String`'s length, or if it does not
1296 /// lie on a [`char`] boundary.
1298 /// [`char`]: ../../std/primitive.char.html
1305 /// let mut s = String::with_capacity(3);
1307 /// s.insert(0, 'f');
1308 /// s.insert(1, 'o');
1309 /// s.insert(2, 'o');
1311 /// assert_eq!("foo", s);
1314 #[stable(feature = "rust1", since = "1.0.0")]
1315 pub fn insert(&mut self, idx: usize, ch: char) {
1316 assert!(self.is_char_boundary(idx));
1317 let mut bits = [0; 4];
1318 let bits = ch.encode_utf8(&mut bits).as_bytes();
1321 self.insert_bytes(idx, bits);
1325 unsafe fn insert_bytes(&mut self, idx: usize, bytes: &[u8]) {
1326 let len = self.len();
1327 let amt = bytes.len();
1328 self.vec.reserve(amt);
1330 ptr::copy(self.vec.as_ptr().add(idx), self.vec.as_mut_ptr().add(idx + amt), len - idx);
1331 ptr::copy(bytes.as_ptr(), self.vec.as_mut_ptr().add(idx), amt);
1332 self.vec.set_len(len + amt);
1335 /// Inserts a string slice into this `String` at a byte position.
1337 /// This is an `O(n)` operation as it requires copying every element in the
1342 /// Panics if `idx` is larger than the `String`'s length, or if it does not
1343 /// lie on a [`char`] boundary.
1345 /// [`char`]: ../../std/primitive.char.html
1352 /// let mut s = String::from("bar");
1354 /// s.insert_str(0, "foo");
1356 /// assert_eq!("foobar", s);
1359 #[stable(feature = "insert_str", since = "1.16.0")]
1360 pub fn insert_str(&mut self, idx: usize, string: &str) {
1361 assert!(self.is_char_boundary(idx));
1364 self.insert_bytes(idx, string.as_bytes());
1368 /// Returns a mutable reference to the contents of this `String`.
1372 /// This function is unsafe because it does not check that the bytes passed
1373 /// to it are valid UTF-8. If this constraint is violated, it may cause
1374 /// memory unsafety issues with future users of the `String`, as the rest of
1375 /// the standard library assumes that `String`s are valid UTF-8.
1382 /// let mut s = String::from("hello");
1385 /// let vec = s.as_mut_vec();
1386 /// assert_eq!(&[104, 101, 108, 108, 111][..], &vec[..]);
1390 /// assert_eq!(s, "olleh");
1393 #[stable(feature = "rust1", since = "1.0.0")]
1394 pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1398 /// Returns the length of this `String`, in bytes, not [`char`]s or
1399 /// graphemes. In other words, it may not be what a human considers the
1400 /// length of the string.
1407 /// let a = String::from("foo");
1408 /// assert_eq!(a.len(), 3);
1410 /// let fancy_f = String::from("ƒoo");
1411 /// assert_eq!(fancy_f.len(), 4);
1412 /// assert_eq!(fancy_f.chars().count(), 3);
1415 #[stable(feature = "rust1", since = "1.0.0")]
1416 pub fn len(&self) -> usize {
1420 /// Returns `true` if this `String` has a length of zero, and `false` otherwise.
1427 /// let mut v = String::new();
1428 /// assert!(v.is_empty());
1431 /// assert!(!v.is_empty());
1434 #[stable(feature = "rust1", since = "1.0.0")]
1435 pub fn is_empty(&self) -> bool {
1439 /// Splits the string into two at the given index.
1441 /// Returns a newly allocated `String`. `self` contains bytes `[0, at)`, and
1442 /// the returned `String` contains bytes `[at, len)`. `at` must be on the
1443 /// boundary of a UTF-8 code point.
1445 /// Note that the capacity of `self` does not change.
1449 /// Panics if `at` is not on a `UTF-8` code point boundary, or if it is beyond the last
1450 /// code point of the string.
1456 /// let mut hello = String::from("Hello, World!");
1457 /// let world = hello.split_off(7);
1458 /// assert_eq!(hello, "Hello, ");
1459 /// assert_eq!(world, "World!");
1463 #[stable(feature = "string_split_off", since = "1.16.0")]
1464 pub fn split_off(&mut self, at: usize) -> String {
1465 assert!(self.is_char_boundary(at));
1466 let other = self.vec.split_off(at);
1467 unsafe { String::from_utf8_unchecked(other) }
1470 /// Truncates this `String`, removing all contents.
1472 /// While this means the `String` will have a length of zero, it does not
1473 /// touch its capacity.
1480 /// let mut s = String::from("foo");
1484 /// assert!(s.is_empty());
1485 /// assert_eq!(0, s.len());
1486 /// assert_eq!(3, s.capacity());
1489 #[stable(feature = "rust1", since = "1.0.0")]
1490 pub fn clear(&mut self) {
1494 /// Creates a draining iterator that removes the specified range in the `String`
1495 /// and yields the removed `chars`.
1497 /// Note: The element range is removed even if the iterator is not
1498 /// consumed until the end.
1502 /// Panics if the starting point or end point do not lie on a [`char`]
1503 /// boundary, or if they're out of bounds.
1505 /// [`char`]: ../../std/primitive.char.html
1512 /// let mut s = String::from("α is alpha, β is beta");
1513 /// let beta_offset = s.find('β').unwrap_or(s.len());
1515 /// // Remove the range up until the β from the string
1516 /// let t: String = s.drain(..beta_offset).collect();
1517 /// assert_eq!(t, "α is alpha, ");
1518 /// assert_eq!(s, "β is beta");
1520 /// // A full range clears the string
1522 /// assert_eq!(s, "");
1524 #[stable(feature = "drain", since = "1.6.0")]
1525 pub fn drain<R>(&mut self, range: R) -> Drain<'_>
1527 R: RangeBounds<usize>,
1531 // The String version of Drain does not have the memory safety issues
1532 // of the vector version. The data is just plain bytes.
1533 // Because the range removal happens in Drop, if the Drain iterator is leaked,
1534 // the removal will not happen.
1535 let len = self.len();
1536 let start = match range.start_bound() {
1538 Excluded(&n) => n + 1,
1541 let end = match range.end_bound() {
1542 Included(&n) => n + 1,
1547 // Take out two simultaneous borrows. The &mut String won't be accessed
1548 // until iteration is over, in Drop.
1549 let self_ptr = self as *mut _;
1550 // slicing does the appropriate bounds checks
1551 let chars_iter = self[start..end].chars();
1553 Drain { start, end, iter: chars_iter, string: self_ptr }
1556 /// Removes the specified range in the string,
1557 /// and replaces it with the given string.
1558 /// The given string doesn't need to be the same length as the range.
1562 /// Panics if the starting point or end point do not lie on a [`char`]
1563 /// boundary, or if they're out of bounds.
1565 /// [`char`]: ../../std/primitive.char.html
1566 /// [`Vec::splice`]: ../../std/vec/struct.Vec.html#method.splice
1573 /// let mut s = String::from("α is alpha, β is beta");
1574 /// let beta_offset = s.find('β').unwrap_or(s.len());
1576 /// // Replace the range up until the β from the string
1577 /// s.replace_range(..beta_offset, "Α is capital alpha; ");
1578 /// assert_eq!(s, "Α is capital alpha; β is beta");
1580 #[stable(feature = "splice", since = "1.27.0")]
1581 pub fn replace_range<R>(&mut self, range: R, replace_with: &str)
1583 R: RangeBounds<usize>,
1587 // Replace_range does not have the memory safety issues of a vector Splice.
1588 // of the vector version. The data is just plain bytes.
1590 match range.start_bound() {
1591 Included(&n) => assert!(self.is_char_boundary(n)),
1592 Excluded(&n) => assert!(self.is_char_boundary(n + 1)),
1595 match range.end_bound() {
1596 Included(&n) => assert!(self.is_char_boundary(n + 1)),
1597 Excluded(&n) => assert!(self.is_char_boundary(n)),
1601 unsafe { self.as_mut_vec() }.splice(range, replace_with.bytes());
1604 /// Converts this `String` into a [`Box`]`<`[`str`]`>`.
1606 /// This will drop any excess capacity.
1608 /// [`Box`]: ../../std/boxed/struct.Box.html
1609 /// [`str`]: ../../std/primitive.str.html
1616 /// let s = String::from("hello");
1618 /// let b = s.into_boxed_str();
1620 #[stable(feature = "box_str", since = "1.4.0")]
1622 pub fn into_boxed_str(self) -> Box<str> {
1623 let slice = self.vec.into_boxed_slice();
1624 unsafe { from_boxed_utf8_unchecked(slice) }
1628 impl FromUtf8Error {
1629 /// Returns a slice of [`u8`]s bytes that were attempted to convert to a `String`.
1636 /// // some invalid bytes, in a vector
1637 /// let bytes = vec![0, 159];
1639 /// let value = String::from_utf8(bytes);
1641 /// assert_eq!(&[0, 159], value.unwrap_err().as_bytes());
1643 #[stable(feature = "from_utf8_error_as_bytes", since = "1.26.0")]
1644 pub fn as_bytes(&self) -> &[u8] {
1648 /// Returns the bytes that were attempted to convert to a `String`.
1650 /// This method is carefully constructed to avoid allocation. It will
1651 /// consume the error, moving out the bytes, so that a copy of the bytes
1652 /// does not need to be made.
1659 /// // some invalid bytes, in a vector
1660 /// let bytes = vec![0, 159];
1662 /// let value = String::from_utf8(bytes);
1664 /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
1666 #[stable(feature = "rust1", since = "1.0.0")]
1667 pub fn into_bytes(self) -> Vec<u8> {
1671 /// Fetch a `Utf8Error` to get more details about the conversion failure.
1673 /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
1674 /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
1675 /// an analogue to `FromUtf8Error`. See its documentation for more details
1678 /// [`Utf8Error`]: ../../std/str/struct.Utf8Error.html
1679 /// [`std::str`]: ../../std/str/index.html
1680 /// [`u8`]: ../../std/primitive.u8.html
1681 /// [`&str`]: ../../std/primitive.str.html
1688 /// // some invalid bytes, in a vector
1689 /// let bytes = vec![0, 159];
1691 /// let error = String::from_utf8(bytes).unwrap_err().utf8_error();
1693 /// // the first byte is invalid here
1694 /// assert_eq!(1, error.valid_up_to());
1696 #[stable(feature = "rust1", since = "1.0.0")]
1697 pub fn utf8_error(&self) -> Utf8Error {
1702 #[stable(feature = "rust1", since = "1.0.0")]
1703 impl fmt::Display for FromUtf8Error {
1704 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1705 fmt::Display::fmt(&self.error, f)
1709 #[stable(feature = "rust1", since = "1.0.0")]
1710 impl fmt::Display for FromUtf16Error {
1711 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1712 fmt::Display::fmt("invalid utf-16: lone surrogate found", f)
1716 #[stable(feature = "rust1", since = "1.0.0")]
1717 impl Clone for String {
1718 fn clone(&self) -> Self {
1719 String { vec: self.vec.clone() }
1722 fn clone_from(&mut self, source: &Self) {
1723 self.vec.clone_from(&source.vec);
1727 #[stable(feature = "rust1", since = "1.0.0")]
1728 impl FromIterator<char> for String {
1729 fn from_iter<I: IntoIterator<Item = char>>(iter: I) -> String {
1730 let mut buf = String::new();
1736 #[stable(feature = "string_from_iter_by_ref", since = "1.17.0")]
1737 impl<'a> FromIterator<&'a char> for String {
1738 fn from_iter<I: IntoIterator<Item = &'a char>>(iter: I) -> String {
1739 let mut buf = String::new();
1745 #[stable(feature = "rust1", since = "1.0.0")]
1746 impl<'a> FromIterator<&'a str> for String {
1747 fn from_iter<I: IntoIterator<Item = &'a str>>(iter: I) -> String {
1748 let mut buf = String::new();
1754 #[stable(feature = "extend_string", since = "1.4.0")]
1755 impl FromIterator<String> for String {
1756 fn from_iter<I: IntoIterator<Item = String>>(iter: I) -> String {
1757 let mut iterator = iter.into_iter();
1759 // Because we're iterating over `String`s, we can avoid at least
1760 // one allocation by getting the first string from the iterator
1761 // and appending to it all the subsequent strings.
1762 match iterator.next() {
1763 None => String::new(),
1765 buf.extend(iterator);
1772 #[stable(feature = "herd_cows", since = "1.19.0")]
1773 impl<'a> FromIterator<Cow<'a, str>> for String {
1774 fn from_iter<I: IntoIterator<Item = Cow<'a, str>>>(iter: I) -> String {
1775 let mut iterator = iter.into_iter();
1777 // Because we're iterating over CoWs, we can (potentially) avoid at least
1778 // one allocation by getting the first item and appending to it all the
1779 // subsequent items.
1780 match iterator.next() {
1781 None => String::new(),
1783 let mut buf = cow.into_owned();
1784 buf.extend(iterator);
1791 #[stable(feature = "rust1", since = "1.0.0")]
1792 impl Extend<char> for String {
1793 fn extend<I: IntoIterator<Item = char>>(&mut self, iter: I) {
1794 let iterator = iter.into_iter();
1795 let (lower_bound, _) = iterator.size_hint();
1796 self.reserve(lower_bound);
1797 iterator.for_each(move |c| self.push(c));
1801 #[stable(feature = "extend_ref", since = "1.2.0")]
1802 impl<'a> Extend<&'a char> for String {
1803 fn extend<I: IntoIterator<Item = &'a char>>(&mut self, iter: I) {
1804 self.extend(iter.into_iter().cloned());
1808 #[stable(feature = "rust1", since = "1.0.0")]
1809 impl<'a> Extend<&'a str> for String {
1810 fn extend<I: IntoIterator<Item = &'a str>>(&mut self, iter: I) {
1811 iter.into_iter().for_each(move |s| self.push_str(s));
1815 #[stable(feature = "extend_string", since = "1.4.0")]
1816 impl Extend<String> for String {
1817 fn extend<I: IntoIterator<Item = String>>(&mut self, iter: I) {
1818 iter.into_iter().for_each(move |s| self.push_str(&s));
1822 #[stable(feature = "herd_cows", since = "1.19.0")]
1823 impl<'a> Extend<Cow<'a, str>> for String {
1824 fn extend<I: IntoIterator<Item = Cow<'a, str>>>(&mut self, iter: I) {
1825 iter.into_iter().for_each(move |s| self.push_str(&s));
1829 /// A convenience impl that delegates to the impl for `&str`
1831 feature = "pattern",
1832 reason = "API not fully fleshed out and ready to be stabilized",
1835 impl<'a, 'b> Pattern<'a> for &'b String {
1836 type Searcher = <&'b str as Pattern<'a>>::Searcher;
1838 fn into_searcher(self, haystack: &'a str) -> <&'b str as Pattern<'a>>::Searcher {
1839 self[..].into_searcher(haystack)
1843 fn is_contained_in(self, haystack: &'a str) -> bool {
1844 self[..].is_contained_in(haystack)
1848 fn is_prefix_of(self, haystack: &'a str) -> bool {
1849 self[..].is_prefix_of(haystack)
1853 #[stable(feature = "rust1", since = "1.0.0")]
1854 impl PartialEq for String {
1856 fn eq(&self, other: &String) -> bool {
1857 PartialEq::eq(&self[..], &other[..])
1860 fn ne(&self, other: &String) -> bool {
1861 PartialEq::ne(&self[..], &other[..])
1865 macro_rules! impl_eq {
1866 ($lhs:ty, $rhs: ty) => {
1867 #[stable(feature = "rust1", since = "1.0.0")]
1868 #[allow(unused_lifetimes)]
1869 impl<'a, 'b> PartialEq<$rhs> for $lhs {
1871 fn eq(&self, other: &$rhs) -> bool {
1872 PartialEq::eq(&self[..], &other[..])
1875 fn ne(&self, other: &$rhs) -> bool {
1876 PartialEq::ne(&self[..], &other[..])
1880 #[stable(feature = "rust1", since = "1.0.0")]
1881 #[allow(unused_lifetimes)]
1882 impl<'a, 'b> PartialEq<$lhs> for $rhs {
1884 fn eq(&self, other: &$lhs) -> bool {
1885 PartialEq::eq(&self[..], &other[..])
1888 fn ne(&self, other: &$lhs) -> bool {
1889 PartialEq::ne(&self[..], &other[..])
1895 impl_eq! { String, str }
1896 impl_eq! { String, &'a str }
1897 impl_eq! { Cow<'a, str>, str }
1898 impl_eq! { Cow<'a, str>, &'b str }
1899 impl_eq! { Cow<'a, str>, String }
1901 #[stable(feature = "rust1", since = "1.0.0")]
1902 impl Default for String {
1903 /// Creates an empty `String`.
1905 fn default() -> String {
1910 #[stable(feature = "rust1", since = "1.0.0")]
1911 impl fmt::Display for String {
1913 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1914 fmt::Display::fmt(&**self, f)
1918 #[stable(feature = "rust1", since = "1.0.0")]
1919 impl fmt::Debug for String {
1921 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1922 fmt::Debug::fmt(&**self, f)
1926 #[stable(feature = "rust1", since = "1.0.0")]
1927 impl hash::Hash for String {
1929 fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
1930 (**self).hash(hasher)
1934 /// Implements the `+` operator for concatenating two strings.
1936 /// This consumes the `String` on the left-hand side and re-uses its buffer (growing it if
1937 /// necessary). This is done to avoid allocating a new `String` and copying the entire contents on
1938 /// every operation, which would lead to `O(n^2)` running time when building an `n`-byte string by
1939 /// repeated concatenation.
1941 /// The string on the right-hand side is only borrowed; its contents are copied into the returned
1946 /// Concatenating two `String`s takes the first by value and borrows the second:
1949 /// let a = String::from("hello");
1950 /// let b = String::from(" world");
1952 /// // `a` is moved and can no longer be used here.
1955 /// If you want to keep using the first `String`, you can clone it and append to the clone instead:
1958 /// let a = String::from("hello");
1959 /// let b = String::from(" world");
1960 /// let c = a.clone() + &b;
1961 /// // `a` is still valid here.
1964 /// Concatenating `&str` slices can be done by converting the first to a `String`:
1967 /// let a = "hello";
1968 /// let b = " world";
1969 /// let c = a.to_string() + b;
1971 #[stable(feature = "rust1", since = "1.0.0")]
1972 impl Add<&str> for String {
1973 type Output = String;
1976 fn add(mut self, other: &str) -> String {
1977 self.push_str(other);
1982 /// Implements the `+=` operator for appending to a `String`.
1984 /// This has the same behavior as the [`push_str`][String::push_str] method.
1985 #[stable(feature = "stringaddassign", since = "1.12.0")]
1986 impl AddAssign<&str> for String {
1988 fn add_assign(&mut self, other: &str) {
1989 self.push_str(other);
1993 #[stable(feature = "rust1", since = "1.0.0")]
1994 impl ops::Index<ops::Range<usize>> for String {
1998 fn index(&self, index: ops::Range<usize>) -> &str {
2002 #[stable(feature = "rust1", since = "1.0.0")]
2003 impl ops::Index<ops::RangeTo<usize>> for String {
2007 fn index(&self, index: ops::RangeTo<usize>) -> &str {
2011 #[stable(feature = "rust1", since = "1.0.0")]
2012 impl ops::Index<ops::RangeFrom<usize>> for String {
2016 fn index(&self, index: ops::RangeFrom<usize>) -> &str {
2020 #[stable(feature = "rust1", since = "1.0.0")]
2021 impl ops::Index<ops::RangeFull> for String {
2025 fn index(&self, _index: ops::RangeFull) -> &str {
2026 unsafe { str::from_utf8_unchecked(&self.vec) }
2029 #[stable(feature = "inclusive_range", since = "1.26.0")]
2030 impl ops::Index<ops::RangeInclusive<usize>> for String {
2034 fn index(&self, index: ops::RangeInclusive<usize>) -> &str {
2035 Index::index(&**self, index)
2038 #[stable(feature = "inclusive_range", since = "1.26.0")]
2039 impl ops::Index<ops::RangeToInclusive<usize>> for String {
2043 fn index(&self, index: ops::RangeToInclusive<usize>) -> &str {
2044 Index::index(&**self, index)
2048 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2049 impl ops::IndexMut<ops::Range<usize>> for String {
2051 fn index_mut(&mut self, index: ops::Range<usize>) -> &mut str {
2052 &mut self[..][index]
2055 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2056 impl ops::IndexMut<ops::RangeTo<usize>> for String {
2058 fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut str {
2059 &mut self[..][index]
2062 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2063 impl ops::IndexMut<ops::RangeFrom<usize>> for String {
2065 fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut str {
2066 &mut self[..][index]
2069 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2070 impl ops::IndexMut<ops::RangeFull> for String {
2072 fn index_mut(&mut self, _index: ops::RangeFull) -> &mut str {
2073 unsafe { str::from_utf8_unchecked_mut(&mut *self.vec) }
2076 #[stable(feature = "inclusive_range", since = "1.26.0")]
2077 impl ops::IndexMut<ops::RangeInclusive<usize>> for String {
2079 fn index_mut(&mut self, index: ops::RangeInclusive<usize>) -> &mut str {
2080 IndexMut::index_mut(&mut **self, index)
2083 #[stable(feature = "inclusive_range", since = "1.26.0")]
2084 impl ops::IndexMut<ops::RangeToInclusive<usize>> for String {
2086 fn index_mut(&mut self, index: ops::RangeToInclusive<usize>) -> &mut str {
2087 IndexMut::index_mut(&mut **self, index)
2091 #[stable(feature = "rust1", since = "1.0.0")]
2092 impl ops::Deref for String {
2096 fn deref(&self) -> &str {
2097 unsafe { str::from_utf8_unchecked(&self.vec) }
2101 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2102 impl ops::DerefMut for String {
2104 fn deref_mut(&mut self) -> &mut str {
2105 unsafe { str::from_utf8_unchecked_mut(&mut *self.vec) }
2109 /// An error when parsing a `String`.
2111 /// This `enum` is slightly awkward: it will never actually exist. This error is
2112 /// part of the type signature of the implementation of [`FromStr`] on
2113 /// [`String`]. The return type of [`from_str`], requires that an error be
2114 /// defined, but, given that a [`String`] can always be made into a new
2115 /// [`String`] without error, this type will never actually be returned. As
2116 /// such, it is only here to satisfy said signature, and is useless otherwise.
2118 /// [`FromStr`]: ../../std/str/trait.FromStr.html
2119 /// [`String`]: struct.String.html
2120 /// [`from_str`]: ../../std/str/trait.FromStr.html#tymethod.from_str
2121 #[stable(feature = "str_parse_error", since = "1.5.0")]
2122 pub type ParseError = core::convert::Infallible;
2124 #[stable(feature = "rust1", since = "1.0.0")]
2125 impl FromStr for String {
2126 type Err = core::convert::Infallible;
2128 fn from_str(s: &str) -> Result<String, ParseError> {
2133 /// A trait for converting a value to a `String`.
2135 /// This trait is automatically implemented for any type which implements the
2136 /// [`Display`] trait. As such, `ToString` shouldn't be implemented directly:
2137 /// [`Display`] should be implemented instead, and you get the `ToString`
2138 /// implementation for free.
2140 /// [`Display`]: ../../std/fmt/trait.Display.html
2141 #[stable(feature = "rust1", since = "1.0.0")]
2142 pub trait ToString {
2143 /// Converts the given value to a `String`.
2151 /// let five = String::from("5");
2153 /// assert_eq!(five, i.to_string());
2155 #[rustc_conversion_suggestion]
2156 #[stable(feature = "rust1", since = "1.0.0")]
2157 fn to_string(&self) -> String;
2162 /// In this implementation, the `to_string` method panics
2163 /// if the `Display` implementation returns an error.
2164 /// This indicates an incorrect `Display` implementation
2165 /// since `fmt::Write for String` never returns an error itself.
2166 #[stable(feature = "rust1", since = "1.0.0")]
2167 impl<T: fmt::Display + ?Sized> ToString for T {
2169 default fn to_string(&self) -> String {
2171 let mut buf = String::new();
2172 buf.write_fmt(format_args!("{}", self))
2173 .expect("a Display implementation returned an error unexpectedly");
2174 buf.shrink_to_fit();
2179 #[stable(feature = "str_to_string_specialization", since = "1.9.0")]
2180 impl ToString for str {
2182 fn to_string(&self) -> String {
2187 #[stable(feature = "cow_str_to_string_specialization", since = "1.17.0")]
2188 impl ToString for Cow<'_, str> {
2190 fn to_string(&self) -> String {
2195 #[stable(feature = "string_to_string_specialization", since = "1.17.0")]
2196 impl ToString for String {
2198 fn to_string(&self) -> String {
2203 #[stable(feature = "rust1", since = "1.0.0")]
2204 impl AsRef<str> for String {
2206 fn as_ref(&self) -> &str {
2211 #[stable(feature = "rust1", since = "1.0.0")]
2212 impl AsRef<[u8]> for String {
2214 fn as_ref(&self) -> &[u8] {
2219 #[stable(feature = "rust1", since = "1.0.0")]
2220 impl From<&str> for String {
2222 fn from(s: &str) -> String {
2227 #[stable(feature = "from_ref_string", since = "1.35.0")]
2228 impl From<&String> for String {
2230 fn from(s: &String) -> String {
2235 // note: test pulls in libstd, which causes errors here
2237 #[stable(feature = "string_from_box", since = "1.18.0")]
2238 impl From<Box<str>> for String {
2239 /// Converts the given boxed `str` slice to a `String`.
2240 /// It is notable that the `str` slice is owned.
2247 /// let s1: String = String::from("hello world");
2248 /// let s2: Box<str> = s1.into_boxed_str();
2249 /// let s3: String = String::from(s2);
2251 /// assert_eq!("hello world", s3)
2253 fn from(s: Box<str>) -> String {
2258 #[stable(feature = "box_from_str", since = "1.20.0")]
2259 impl From<String> for Box<str> {
2260 /// Converts the given `String` to a boxed `str` slice that is owned.
2267 /// let s1: String = String::from("hello world");
2268 /// let s2: Box<str> = Box::from(s1);
2269 /// let s3: String = String::from(s2);
2271 /// assert_eq!("hello world", s3)
2273 fn from(s: String) -> Box<str> {
2278 #[stable(feature = "string_from_cow_str", since = "1.14.0")]
2279 impl<'a> From<Cow<'a, str>> for String {
2280 fn from(s: Cow<'a, str>) -> String {
2285 #[stable(feature = "rust1", since = "1.0.0")]
2286 impl<'a> From<&'a str> for Cow<'a, str> {
2288 fn from(s: &'a str) -> Cow<'a, str> {
2293 #[stable(feature = "rust1", since = "1.0.0")]
2294 impl<'a> From<String> for Cow<'a, str> {
2296 fn from(s: String) -> Cow<'a, str> {
2301 #[stable(feature = "cow_from_string_ref", since = "1.28.0")]
2302 impl<'a> From<&'a String> for Cow<'a, str> {
2304 fn from(s: &'a String) -> Cow<'a, str> {
2305 Cow::Borrowed(s.as_str())
2309 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2310 impl<'a> FromIterator<char> for Cow<'a, str> {
2311 fn from_iter<I: IntoIterator<Item = char>>(it: I) -> Cow<'a, str> {
2312 Cow::Owned(FromIterator::from_iter(it))
2316 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2317 impl<'a, 'b> FromIterator<&'b str> for Cow<'a, str> {
2318 fn from_iter<I: IntoIterator<Item = &'b str>>(it: I) -> Cow<'a, str> {
2319 Cow::Owned(FromIterator::from_iter(it))
2323 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2324 impl<'a> FromIterator<String> for Cow<'a, str> {
2325 fn from_iter<I: IntoIterator<Item = String>>(it: I) -> Cow<'a, str> {
2326 Cow::Owned(FromIterator::from_iter(it))
2330 #[stable(feature = "from_string_for_vec_u8", since = "1.14.0")]
2331 impl From<String> for Vec<u8> {
2332 /// Converts the given `String` to a vector `Vec` that holds values of type `u8`.
2339 /// let s1 = String::from("hello world");
2340 /// let v1 = Vec::from(s1);
2343 /// println!("{}", b);
2346 fn from(string: String) -> Vec<u8> {
2351 #[stable(feature = "rust1", since = "1.0.0")]
2352 impl fmt::Write for String {
2354 fn write_str(&mut self, s: &str) -> fmt::Result {
2360 fn write_char(&mut self, c: char) -> fmt::Result {
2366 /// A draining iterator for `String`.
2368 /// This struct is created by the [`drain`] method on [`String`]. See its
2369 /// documentation for more.
2371 /// [`drain`]: struct.String.html#method.drain
2372 /// [`String`]: struct.String.html
2373 #[stable(feature = "drain", since = "1.6.0")]
2374 pub struct Drain<'a> {
2375 /// Will be used as &'a mut String in the destructor
2376 string: *mut String,
2377 /// Start of part to remove
2379 /// End of part to remove
2381 /// Current remaining range to remove
2385 #[stable(feature = "collection_debug", since = "1.17.0")]
2386 impl fmt::Debug for Drain<'_> {
2387 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2388 f.pad("Drain { .. }")
2392 #[stable(feature = "drain", since = "1.6.0")]
2393 unsafe impl Sync for Drain<'_> {}
2394 #[stable(feature = "drain", since = "1.6.0")]
2395 unsafe impl Send for Drain<'_> {}
2397 #[stable(feature = "drain", since = "1.6.0")]
2398 impl Drop for Drain<'_> {
2399 fn drop(&mut self) {
2401 // Use Vec::drain. "Reaffirm" the bounds checks to avoid
2402 // panic code being inserted again.
2403 let self_vec = (*self.string).as_mut_vec();
2404 if self.start <= self.end && self.end <= self_vec.len() {
2405 self_vec.drain(self.start..self.end);
2411 #[stable(feature = "drain", since = "1.6.0")]
2412 impl Iterator for Drain<'_> {
2416 fn next(&mut self) -> Option<char> {
2420 fn size_hint(&self) -> (usize, Option<usize>) {
2421 self.iter.size_hint()
2425 fn last(mut self) -> Option<char> {
2430 #[stable(feature = "drain", since = "1.6.0")]
2431 impl DoubleEndedIterator for Drain<'_> {
2433 fn next_back(&mut self) -> Option<char> {
2434 self.iter.next_back()
2438 #[stable(feature = "fused", since = "1.26.0")]
2439 impl FusedIterator for Drain<'_> {}