1 //! A UTF-8 encoded, growable string.
3 //! This module contains the [`String`] type, a trait for converting
4 //! [`ToString`]s, and several error types that may result from working with
7 //! [`ToString`]: trait.ToString.html
11 //! There are multiple ways to create a new [`String`] from a string literal:
14 //! let s = "Hello".to_string();
16 //! let s = String::from("world");
17 //! let s: String = "also this".into();
20 //! You can create a new [`String`] from an existing one by concatenating with
23 //! [`String`]: struct.String.html
26 //! let s = "Hello".to_string();
28 //! let message = s + " world!";
31 //! If you have a vector of valid UTF-8 bytes, you can make a [`String`] out of
32 //! it. You can do the reverse too.
35 //! let sparkle_heart = vec![240, 159, 146, 150];
37 //! // We know these bytes are valid, so we'll use `unwrap()`.
38 //! let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
40 //! assert_eq!("💖", sparkle_heart);
42 //! let bytes = sparkle_heart.into_bytes();
44 //! assert_eq!(bytes, [240, 159, 146, 150]);
47 #![stable(feature = "rust1", since = "1.0.0")]
49 use core::char::{decode_utf16, REPLACEMENT_CHARACTER};
52 use core::iter::{FromIterator, FusedIterator};
53 use core::ops::{self, Add, AddAssign, Index, IndexMut, RangeBounds};
54 use core::ops::Bound::{Excluded, Included, Unbounded};
56 use core::str::{pattern::Pattern, lossy};
58 use crate::borrow::{Cow, ToOwned};
59 use crate::collections::TryReserveError;
60 use crate::boxed::Box;
61 use crate::str::{self, from_boxed_utf8_unchecked, FromStr, Utf8Error, Chars};
64 /// A UTF-8 encoded, growable string.
66 /// The `String` type is the most common string type that has ownership over the
67 /// contents of the string. It has a close relationship with its borrowed
68 /// counterpart, the primitive [`str`].
70 /// [`str`]: ../../std/primitive.str.html
74 /// You can create a `String` from a literal string with [`String::from`]:
77 /// let hello = String::from("Hello, world!");
80 /// You can append a [`char`] to a `String` with the [`push`] method, and
81 /// append a [`&str`] with the [`push_str`] method:
84 /// let mut hello = String::from("Hello, ");
87 /// hello.push_str("orld!");
90 /// [`String::from`]: #method.from
91 /// [`char`]: ../../std/primitive.char.html
92 /// [`push`]: #method.push
93 /// [`push_str`]: #method.push_str
95 /// If you have a vector of UTF-8 bytes, you can create a `String` from it with
96 /// the [`from_utf8`] method:
99 /// // some bytes, in a vector
100 /// let sparkle_heart = vec![240, 159, 146, 150];
102 /// // We know these bytes are valid, so we'll use `unwrap()`.
103 /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
105 /// assert_eq!("💖", sparkle_heart);
108 /// [`from_utf8`]: #method.from_utf8
112 /// `String`s are always valid UTF-8. This has a few implications, the first of
113 /// which is that if you need a non-UTF-8 string, consider [`OsString`]. It is
114 /// similar, but without the UTF-8 constraint. The second implication is that
115 /// you cannot index into a `String`:
117 /// ```compile_fail,E0277
120 /// println!("The first letter of s is {}", s[0]); // ERROR!!!
123 /// [`OsString`]: ../../std/ffi/struct.OsString.html
125 /// Indexing is intended to be a constant-time operation, but UTF-8 encoding
126 /// does not allow us to do this. Furthermore, it's not clear what sort of
127 /// thing the index should return: a byte, a codepoint, or a grapheme cluster.
128 /// The [`bytes`] and [`chars`] methods return iterators over the first
129 /// two, respectively.
131 /// [`bytes`]: #method.bytes
132 /// [`chars`]: #method.chars
136 /// `String`s implement [`Deref`]`<Target=str>`, and so inherit all of [`str`]'s
137 /// methods. In addition, this means that you can pass a `String` to a
138 /// function which takes a [`&str`] by using an ampersand (`&`):
141 /// fn takes_str(s: &str) { }
143 /// let s = String::from("Hello");
148 /// This will create a [`&str`] from the `String` and pass it in. This
149 /// conversion is very inexpensive, and so generally, functions will accept
150 /// [`&str`]s as arguments unless they need a `String` for some specific
153 /// In certain cases Rust doesn't have enough information to make this
154 /// conversion, known as [`Deref`] coercion. In the following example a string
155 /// slice [`&'a str`][`&str`] implements the trait `TraitExample`, and the function
156 /// `example_func` takes anything that implements the trait. In this case Rust
157 /// would need to make two implicit conversions, which Rust doesn't have the
158 /// means to do. For that reason, the following example will not compile.
160 /// ```compile_fail,E0277
161 /// trait TraitExample {}
163 /// impl<'a> TraitExample for &'a str {}
165 /// fn example_func<A: TraitExample>(example_arg: A) {}
167 /// let example_string = String::from("example_string");
168 /// example_func(&example_string);
171 /// There are two options that would work instead. The first would be to
172 /// change the line `example_func(&example_string);` to
173 /// `example_func(example_string.as_str());`, using the method [`as_str()`]
174 /// to explicitly extract the string slice containing the string. The second
175 /// way changes `example_func(&example_string);` to
176 /// `example_func(&*example_string);`. In this case we are dereferencing a
177 /// `String` to a [`str`][`&str`], then referencing the [`str`][`&str`] back to
178 /// [`&str`]. The second way is more idiomatic, however both work to do the
179 /// conversion explicitly rather than relying on the implicit conversion.
183 /// A `String` is made up of three components: a pointer to some bytes, a
184 /// length, and a capacity. The pointer points to an internal buffer `String`
185 /// uses to store its data. The length is the number of bytes currently stored
186 /// in the buffer, and the capacity is the size of the buffer in bytes. As such,
187 /// the length will always be less than or equal to the capacity.
189 /// This buffer is always stored on the heap.
191 /// You can look at these with the [`as_ptr`], [`len`], and [`capacity`]
197 /// let story = String::from("Once upon a time...");
199 // FIXME Update this when vec_into_raw_parts is stabilized
200 /// // Prevent automatically dropping the String's data
201 /// let mut story = mem::ManuallyDrop::new(story);
203 /// let ptr = story.as_mut_ptr();
204 /// let len = story.len();
205 /// let capacity = story.capacity();
207 /// // story has nineteen bytes
208 /// assert_eq!(19, len);
210 /// // We can re-build a String out of ptr, len, and capacity. This is all
211 /// // unsafe because we are responsible for making sure the components are
213 /// let s = unsafe { String::from_raw_parts(ptr, len, capacity) } ;
215 /// assert_eq!(String::from("Once upon a time..."), s);
218 /// [`as_ptr`]: #method.as_ptr
219 /// [`len`]: #method.len
220 /// [`capacity`]: #method.capacity
222 /// If a `String` has enough capacity, adding elements to it will not
223 /// re-allocate. For example, consider this program:
226 /// let mut s = String::new();
228 /// println!("{}", s.capacity());
231 /// s.push_str("hello");
232 /// println!("{}", s.capacity());
236 /// This will output the following:
247 /// At first, we have no memory allocated at all, but as we append to the
248 /// string, it increases its capacity appropriately. If we instead use the
249 /// [`with_capacity`] method to allocate the correct capacity initially:
252 /// let mut s = String::with_capacity(25);
254 /// println!("{}", s.capacity());
257 /// s.push_str("hello");
258 /// println!("{}", s.capacity());
262 /// [`with_capacity`]: #method.with_capacity
264 /// We end up with a different output:
275 /// Here, there's no need to allocate more memory inside the loop.
277 /// [`&str`]: ../../std/primitive.str.html
278 /// [`Deref`]: ../../std/ops/trait.Deref.html
279 /// [`as_str()`]: struct.String.html#method.as_str
280 #[derive(PartialOrd, Eq, Ord)]
281 #[stable(feature = "rust1", since = "1.0.0")]
286 /// A possible error value when converting a `String` from a UTF-8 byte vector.
288 /// This type is the error type for the [`from_utf8`] method on [`String`]. It
289 /// is designed in such a way to carefully avoid reallocations: the
290 /// [`into_bytes`] method will give back the byte vector that was used in the
291 /// conversion attempt.
293 /// [`from_utf8`]: struct.String.html#method.from_utf8
294 /// [`String`]: struct.String.html
295 /// [`into_bytes`]: struct.FromUtf8Error.html#method.into_bytes
297 /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
298 /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
299 /// an analogue to `FromUtf8Error`, and you can get one from a `FromUtf8Error`
300 /// through the [`utf8_error`] method.
302 /// [`Utf8Error`]: ../../std/str/struct.Utf8Error.html
303 /// [`std::str`]: ../../std/str/index.html
304 /// [`u8`]: ../../std/primitive.u8.html
305 /// [`&str`]: ../../std/primitive.str.html
306 /// [`utf8_error`]: #method.utf8_error
313 /// // some invalid bytes, in a vector
314 /// let bytes = vec![0, 159];
316 /// let value = String::from_utf8(bytes);
318 /// assert!(value.is_err());
319 /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
321 #[stable(feature = "rust1", since = "1.0.0")]
323 pub struct FromUtf8Error {
328 /// A possible error value when converting a `String` from a UTF-16 byte slice.
330 /// This type is the error type for the [`from_utf16`] method on [`String`].
332 /// [`from_utf16`]: struct.String.html#method.from_utf16
333 /// [`String`]: struct.String.html
340 /// // 𝄞mu<invalid>ic
341 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
342 /// 0xD800, 0x0069, 0x0063];
344 /// assert!(String::from_utf16(v).is_err());
346 #[stable(feature = "rust1", since = "1.0.0")]
348 pub struct FromUtf16Error(());
351 /// Creates a new empty `String`.
353 /// Given that the `String` is empty, this will not allocate any initial
354 /// buffer. While that means that this initial operation is very
355 /// inexpensive, it may cause excessive allocation later when you add
356 /// data. If you have an idea of how much data the `String` will hold,
357 /// consider the [`with_capacity`] method to prevent excessive
360 /// [`with_capacity`]: #method.with_capacity
367 /// let s = String::new();
370 #[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 }),
503 /// Converts a slice of bytes to a string, including invalid characters.
505 /// Strings are made of bytes ([`u8`]), and a slice of bytes
506 /// ([`&[u8]`][byteslice]) is made of bytes, so this function converts
507 /// between the two. Not all byte slices are valid strings, however: strings
508 /// are required to be valid UTF-8. During this conversion,
509 /// `from_utf8_lossy()` will replace any invalid UTF-8 sequences with
510 /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD], which looks like this: �
512 /// [`u8`]: ../../std/primitive.u8.html
513 /// [byteslice]: ../../std/primitive.slice.html
514 /// [U+FFFD]: ../char/constant.REPLACEMENT_CHARACTER.html
516 /// If you are sure that the byte slice is valid UTF-8, and you don't want
517 /// to incur the overhead of the conversion, there is an unsafe version
518 /// of this function, [`from_utf8_unchecked`], which has the same behavior
519 /// but skips the checks.
521 /// [`from_utf8_unchecked`]: struct.String.html#method.from_utf8_unchecked
523 /// This function returns a [`Cow<'a, str>`]. If our byte slice is invalid
524 /// UTF-8, then we need to insert the replacement characters, which will
525 /// change the size of the string, and hence, require a `String`. But if
526 /// it's already valid UTF-8, we don't need a new allocation. This return
527 /// type allows us to handle both cases.
529 /// [`Cow<'a, str>`]: ../../std/borrow/enum.Cow.html
536 /// // some bytes, in a vector
537 /// let sparkle_heart = vec![240, 159, 146, 150];
539 /// let sparkle_heart = String::from_utf8_lossy(&sparkle_heart);
541 /// assert_eq!("💖", sparkle_heart);
547 /// // some invalid bytes
548 /// let input = b"Hello \xF0\x90\x80World";
549 /// let output = String::from_utf8_lossy(input);
551 /// assert_eq!("Hello �World", output);
553 #[stable(feature = "rust1", since = "1.0.0")]
554 pub fn from_utf8_lossy(v: &[u8]) -> Cow<'_, str> {
555 let mut iter = lossy::Utf8Lossy::from_bytes(v).chunks();
557 let (first_valid, first_broken) = if let Some(chunk) = iter.next() {
558 let lossy::Utf8LossyChunk { valid, broken } = chunk;
559 if valid.len() == v.len() {
560 debug_assert!(broken.is_empty());
561 return Cow::Borrowed(valid);
565 return Cow::Borrowed("");
568 const REPLACEMENT: &str = "\u{FFFD}";
570 let mut res = String::with_capacity(v.len());
571 res.push_str(first_valid);
572 if !first_broken.is_empty() {
573 res.push_str(REPLACEMENT);
576 for lossy::Utf8LossyChunk { valid, broken } in iter {
578 if !broken.is_empty() {
579 res.push_str(REPLACEMENT);
586 /// Decode a UTF-16 encoded vector `v` into a `String`, returning [`Err`]
587 /// if `v` contains any invalid data.
589 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
597 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
598 /// 0x0073, 0x0069, 0x0063];
599 /// assert_eq!(String::from("𝄞music"),
600 /// String::from_utf16(v).unwrap());
602 /// // 𝄞mu<invalid>ic
603 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
604 /// 0xD800, 0x0069, 0x0063];
605 /// assert!(String::from_utf16(v).is_err());
607 #[stable(feature = "rust1", since = "1.0.0")]
608 pub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error> {
609 // This isn't done via collect::<Result<_, _>>() for performance reasons.
610 // FIXME: the function can be simplified again when #48994 is closed.
611 let mut ret = String::with_capacity(v.len());
612 for c in decode_utf16(v.iter().cloned()) {
616 return Err(FromUtf16Error(()));
622 /// Decode a UTF-16 encoded slice `v` into a `String`, replacing
623 /// invalid data with [the replacement character (`U+FFFD`)][U+FFFD].
625 /// Unlike [`from_utf8_lossy`] which returns a [`Cow<'a, str>`],
626 /// `from_utf16_lossy` returns a `String` since the UTF-16 to UTF-8
627 /// conversion requires a memory allocation.
629 /// [`from_utf8_lossy`]: #method.from_utf8_lossy
630 /// [`Cow<'a, str>`]: ../borrow/enum.Cow.html
631 /// [U+FFFD]: ../char/constant.REPLACEMENT_CHARACTER.html
638 /// // 𝄞mus<invalid>ic<invalid>
639 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
640 /// 0x0073, 0xDD1E, 0x0069, 0x0063,
643 /// assert_eq!(String::from("𝄞mus\u{FFFD}ic\u{FFFD}"),
644 /// String::from_utf16_lossy(v));
647 #[stable(feature = "rust1", since = "1.0.0")]
648 pub fn from_utf16_lossy(v: &[u16]) -> String {
649 decode_utf16(v.iter().cloned()).map(|r| r.unwrap_or(REPLACEMENT_CHARACTER)).collect()
652 /// Decomposes a `String` into its raw components.
654 /// Returns the raw pointer to the underlying data, the length of
655 /// the string (in bytes), and the allocated capacity of the data
656 /// (in bytes). These are the same arguments in the same order as
657 /// the arguments to [`from_raw_parts`].
659 /// After calling this function, the caller is responsible for the
660 /// memory previously managed by the `String`. The only way to do
661 /// this is to convert the raw pointer, length, and capacity back
662 /// into a `String` with the [`from_raw_parts`] function, allowing
663 /// the destructor to perform the cleanup.
665 /// [`from_raw_parts`]: #method.from_raw_parts
670 /// #![feature(vec_into_raw_parts)]
671 /// let s = String::from("hello");
673 /// let (ptr, len, cap) = s.into_raw_parts();
675 /// let rebuilt = unsafe { String::from_raw_parts(ptr, len, cap) };
676 /// assert_eq!(rebuilt, "hello");
678 #[unstable(feature = "vec_into_raw_parts", reason = "new API", issue = "65816")]
679 pub fn into_raw_parts(self) -> (*mut u8, usize, usize) {
680 self.vec.into_raw_parts()
683 /// Creates a new `String` from a length, capacity, and pointer.
687 /// This is highly unsafe, due to the number of invariants that aren't
690 /// * The memory at `ptr` needs to have been previously allocated by the
691 /// same allocator the standard library uses, with a required alignment of exactly 1.
692 /// * `length` needs to be less than or equal to `capacity`.
693 /// * `capacity` needs to be the correct value.
695 /// Violating these may cause problems like corrupting the allocator's
696 /// internal data structures.
698 /// The ownership of `ptr` is effectively transferred to the
699 /// `String` which may then deallocate, reallocate or change the
700 /// contents of memory pointed to by the pointer at will. Ensure
701 /// that nothing else uses the pointer after calling this
712 /// let s = String::from("hello");
714 // FIXME Update this when vec_into_raw_parts is stabilized
715 /// // Prevent automatically dropping the String's data
716 /// let mut s = mem::ManuallyDrop::new(s);
718 /// let ptr = s.as_mut_ptr();
719 /// let len = s.len();
720 /// let capacity = s.capacity();
722 /// let s = String::from_raw_parts(ptr, len, capacity);
724 /// assert_eq!(String::from("hello"), s);
728 #[stable(feature = "rust1", since = "1.0.0")]
729 pub unsafe fn from_raw_parts(buf: *mut u8, length: usize, capacity: usize) -> String {
730 String { vec: Vec::from_raw_parts(buf, length, capacity) }
733 /// Converts a vector of bytes to a `String` without checking that the
734 /// string contains valid UTF-8.
736 /// See the safe version, [`from_utf8`], for more details.
738 /// [`from_utf8`]: struct.String.html#method.from_utf8
742 /// This function is unsafe because it does not check that the bytes passed
743 /// to it are valid UTF-8. If this constraint is violated, it may cause
744 /// memory unsafety issues with future users of the `String`, as the rest of
745 /// the standard library assumes that `String`s are valid UTF-8.
752 /// // some bytes, in a vector
753 /// let sparkle_heart = vec![240, 159, 146, 150];
755 /// let sparkle_heart = unsafe {
756 /// String::from_utf8_unchecked(sparkle_heart)
759 /// assert_eq!("💖", sparkle_heart);
762 #[stable(feature = "rust1", since = "1.0.0")]
763 pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String {
764 String { vec: bytes }
767 /// Converts a `String` into a byte vector.
769 /// This consumes the `String`, so we do not need to copy its contents.
776 /// let s = String::from("hello");
777 /// let bytes = s.into_bytes();
779 /// assert_eq!(&[104, 101, 108, 108, 111][..], &bytes[..]);
782 #[stable(feature = "rust1", since = "1.0.0")]
783 pub fn into_bytes(self) -> Vec<u8> {
787 /// Extracts a string slice containing the entire `String`.
794 /// let s = String::from("foo");
796 /// assert_eq!("foo", s.as_str());
799 #[stable(feature = "string_as_str", since = "1.7.0")]
800 pub fn as_str(&self) -> &str {
804 /// Converts a `String` into a mutable string slice.
811 /// let mut s = String::from("foobar");
812 /// let s_mut_str = s.as_mut_str();
814 /// s_mut_str.make_ascii_uppercase();
816 /// assert_eq!("FOOBAR", s_mut_str);
819 #[stable(feature = "string_as_str", since = "1.7.0")]
820 pub fn as_mut_str(&mut self) -> &mut str {
824 /// Appends a given string slice onto the end of this `String`.
831 /// let mut s = String::from("foo");
833 /// s.push_str("bar");
835 /// assert_eq!("foobar", s);
838 #[stable(feature = "rust1", since = "1.0.0")]
839 pub fn push_str(&mut self, string: &str) {
840 self.vec.extend_from_slice(string.as_bytes())
843 /// Returns this `String`'s capacity, in bytes.
850 /// let s = String::with_capacity(10);
852 /// assert!(s.capacity() >= 10);
855 #[stable(feature = "rust1", since = "1.0.0")]
856 pub fn capacity(&self) -> usize {
860 /// Ensures that this `String`'s capacity is at least `additional` bytes
861 /// larger than its length.
863 /// The capacity may be increased by more than `additional` bytes if it
864 /// chooses, to prevent frequent reallocations.
866 /// If you do not want this "at least" behavior, see the [`reserve_exact`]
871 /// Panics if the new capacity overflows [`usize`].
873 /// [`reserve_exact`]: struct.String.html#method.reserve_exact
874 /// [`usize`]: ../../std/primitive.usize.html
881 /// let mut s = String::new();
885 /// assert!(s.capacity() >= 10);
888 /// This may not actually increase the capacity:
891 /// let mut s = String::with_capacity(10);
895 /// // s now has a length of 2 and a capacity of 10
896 /// assert_eq!(2, s.len());
897 /// assert_eq!(10, s.capacity());
899 /// // Since we already have an extra 8 capacity, calling this...
902 /// // ... doesn't actually increase.
903 /// assert_eq!(10, s.capacity());
906 #[stable(feature = "rust1", since = "1.0.0")]
907 pub fn reserve(&mut self, additional: usize) {
908 self.vec.reserve(additional)
911 /// Ensures that this `String`'s capacity is `additional` bytes
912 /// larger than its length.
914 /// Consider using the [`reserve`] method unless you absolutely know
915 /// better than the allocator.
917 /// [`reserve`]: #method.reserve
921 /// Panics if the new capacity overflows `usize`.
928 /// let mut s = String::new();
930 /// s.reserve_exact(10);
932 /// assert!(s.capacity() >= 10);
935 /// This may not actually increase the capacity:
938 /// let mut s = String::with_capacity(10);
942 /// // s now has a length of 2 and a capacity of 10
943 /// assert_eq!(2, s.len());
944 /// assert_eq!(10, s.capacity());
946 /// // Since we already have an extra 8 capacity, calling this...
947 /// s.reserve_exact(8);
949 /// // ... doesn't actually increase.
950 /// assert_eq!(10, s.capacity());
953 #[stable(feature = "rust1", since = "1.0.0")]
954 pub fn reserve_exact(&mut self, additional: usize) {
955 self.vec.reserve_exact(additional)
958 /// Tries to reserve capacity for at least `additional` more elements to be inserted
959 /// in the given `String`. The collection may reserve more space to avoid
960 /// frequent reallocations. After calling `reserve`, capacity will be
961 /// greater than or equal to `self.len() + additional`. Does nothing if
962 /// capacity is already sufficient.
966 /// If the capacity overflows, or the allocator reports a failure, then an error
972 /// #![feature(try_reserve)]
973 /// use std::collections::TryReserveError;
975 /// fn process_data(data: &str) -> Result<String, TryReserveError> {
976 /// let mut output = String::new();
978 /// // Pre-reserve the memory, exiting if we can't
979 /// output.try_reserve(data.len())?;
981 /// // Now we know this can't OOM in the middle of our complex work
982 /// output.push_str(data);
986 /// # process_data("rust").expect("why is the test harness OOMing on 4 bytes?");
988 #[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
989 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
990 self.vec.try_reserve(additional)
993 /// Tries to reserves the minimum capacity for exactly `additional` more elements to
994 /// be inserted in the given `String`. After calling `reserve_exact`,
995 /// capacity will be greater than or equal to `self.len() + additional`.
996 /// Does nothing if the capacity is already sufficient.
998 /// Note that the allocator may give the collection more space than it
999 /// requests. Therefore, capacity can not be relied upon to be precisely
1000 /// minimal. Prefer `reserve` if future insertions are expected.
1004 /// If the capacity overflows, or the allocator reports a failure, then an error
1010 /// #![feature(try_reserve)]
1011 /// use std::collections::TryReserveError;
1013 /// fn process_data(data: &str) -> Result<String, TryReserveError> {
1014 /// let mut output = String::new();
1016 /// // Pre-reserve the memory, exiting if we can't
1017 /// output.try_reserve(data.len())?;
1019 /// // Now we know this can't OOM in the middle of our complex work
1020 /// output.push_str(data);
1024 /// # process_data("rust").expect("why is the test harness OOMing on 4 bytes?");
1026 #[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
1027 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
1028 self.vec.try_reserve_exact(additional)
1031 /// Shrinks the capacity of this `String` to match its length.
1038 /// let mut s = String::from("foo");
1041 /// assert!(s.capacity() >= 100);
1043 /// s.shrink_to_fit();
1044 /// assert_eq!(3, s.capacity());
1047 #[stable(feature = "rust1", since = "1.0.0")]
1048 pub fn shrink_to_fit(&mut self) {
1049 self.vec.shrink_to_fit()
1052 /// Shrinks the capacity of this `String` with a lower bound.
1054 /// The capacity will remain at least as large as both the length
1055 /// and the supplied value.
1057 /// Panics if the current capacity is smaller than the supplied
1058 /// minimum capacity.
1063 /// #![feature(shrink_to)]
1064 /// let mut s = String::from("foo");
1067 /// assert!(s.capacity() >= 100);
1069 /// s.shrink_to(10);
1070 /// assert!(s.capacity() >= 10);
1072 /// assert!(s.capacity() >= 3);
1075 #[unstable(feature = "shrink_to", reason = "new API", issue="56431")]
1076 pub fn shrink_to(&mut self, min_capacity: usize) {
1077 self.vec.shrink_to(min_capacity)
1080 /// Appends the given [`char`] to the end of this `String`.
1082 /// [`char`]: ../../std/primitive.char.html
1089 /// let mut s = String::from("abc");
1095 /// assert_eq!("abc123", s);
1098 #[stable(feature = "rust1", since = "1.0.0")]
1099 pub fn push(&mut self, ch: char) {
1100 match ch.len_utf8() {
1101 1 => self.vec.push(ch as u8),
1102 _ => self.vec.extend_from_slice(ch.encode_utf8(&mut [0; 4]).as_bytes()),
1106 /// Returns a byte slice of this `String`'s contents.
1108 /// The inverse of this method is [`from_utf8`].
1110 /// [`from_utf8`]: #method.from_utf8
1117 /// let s = String::from("hello");
1119 /// assert_eq!(&[104, 101, 108, 108, 111], s.as_bytes());
1122 #[stable(feature = "rust1", since = "1.0.0")]
1123 pub fn as_bytes(&self) -> &[u8] {
1127 /// Shortens this `String` to the specified length.
1129 /// If `new_len` is greater than the string's current length, this has no
1132 /// Note that this method has no effect on the allocated capacity
1137 /// Panics if `new_len` does not lie on a [`char`] boundary.
1139 /// [`char`]: ../../std/primitive.char.html
1146 /// let mut s = String::from("hello");
1150 /// assert_eq!("he", s);
1153 #[stable(feature = "rust1", since = "1.0.0")]
1154 pub fn truncate(&mut self, new_len: usize) {
1155 if new_len <= self.len() {
1156 assert!(self.is_char_boundary(new_len));
1157 self.vec.truncate(new_len)
1161 /// Removes the last character from the string buffer and returns it.
1163 /// Returns [`None`] if this `String` is empty.
1165 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1172 /// let mut s = String::from("foo");
1174 /// assert_eq!(s.pop(), Some('o'));
1175 /// assert_eq!(s.pop(), Some('o'));
1176 /// assert_eq!(s.pop(), Some('f'));
1178 /// assert_eq!(s.pop(), None);
1181 #[stable(feature = "rust1", since = "1.0.0")]
1182 pub fn pop(&mut self) -> Option<char> {
1183 let ch = self.chars().rev().next()?;
1184 let newlen = self.len() - ch.len_utf8();
1186 self.vec.set_len(newlen);
1191 /// Removes a [`char`] from this `String` at a byte position and returns it.
1193 /// This is an `O(n)` operation, as it requires copying every element in the
1198 /// Panics if `idx` is larger than or equal to the `String`'s length,
1199 /// or if it does not lie on a [`char`] boundary.
1201 /// [`char`]: ../../std/primitive.char.html
1208 /// let mut s = String::from("foo");
1210 /// assert_eq!(s.remove(0), 'f');
1211 /// assert_eq!(s.remove(1), 'o');
1212 /// assert_eq!(s.remove(0), 'o');
1215 #[stable(feature = "rust1", since = "1.0.0")]
1216 pub fn remove(&mut self, idx: usize) -> char {
1217 let ch = match self[idx..].chars().next() {
1219 None => panic!("cannot remove a char from the end of a string"),
1222 let next = idx + ch.len_utf8();
1223 let len = self.len();
1225 ptr::copy(self.vec.as_ptr().add(next),
1226 self.vec.as_mut_ptr().add(idx),
1228 self.vec.set_len(len - (next - idx));
1233 /// Retains only the characters specified by the predicate.
1235 /// In other words, remove all characters `c` such that `f(c)` returns `false`.
1236 /// This method operates in place, visiting each character exactly once in the
1237 /// original order, and preserves the order of the retained characters.
1242 /// let mut s = String::from("f_o_ob_ar");
1244 /// s.retain(|c| c != '_');
1246 /// assert_eq!(s, "foobar");
1249 /// The exact order may be useful for tracking external state, like an index.
1252 /// let mut s = String::from("abcde");
1253 /// let keep = [false, true, true, false, true];
1255 /// s.retain(|_| (keep[i], i += 1).0);
1256 /// assert_eq!(s, "bce");
1259 #[stable(feature = "string_retain", since = "1.26.0")]
1260 pub fn retain<F>(&mut self, mut f: F)
1261 where F: FnMut(char) -> bool
1263 let len = self.len();
1264 let mut del_bytes = 0;
1269 self.get_unchecked(idx..len).chars().next().unwrap()
1271 let ch_len = ch.len_utf8();
1274 del_bytes += ch_len;
1275 } else if del_bytes > 0 {
1277 ptr::copy(self.vec.as_ptr().add(idx),
1278 self.vec.as_mut_ptr().add(idx - del_bytes),
1283 // Point idx to the next char
1288 unsafe { self.vec.set_len(len - del_bytes); }
1292 /// Inserts a character into this `String` at a byte position.
1294 /// This is an `O(n)` operation as it requires copying every element in the
1299 /// Panics if `idx` is larger than the `String`'s length, or if it does not
1300 /// lie on a [`char`] boundary.
1302 /// [`char`]: ../../std/primitive.char.html
1309 /// let mut s = String::with_capacity(3);
1311 /// s.insert(0, 'f');
1312 /// s.insert(1, 'o');
1313 /// s.insert(2, 'o');
1315 /// assert_eq!("foo", s);
1318 #[stable(feature = "rust1", since = "1.0.0")]
1319 pub fn insert(&mut self, idx: usize, ch: char) {
1320 assert!(self.is_char_boundary(idx));
1321 let mut bits = [0; 4];
1322 let bits = ch.encode_utf8(&mut bits).as_bytes();
1325 self.insert_bytes(idx, bits);
1329 unsafe fn insert_bytes(&mut self, idx: usize, bytes: &[u8]) {
1330 let len = self.len();
1331 let amt = bytes.len();
1332 self.vec.reserve(amt);
1334 ptr::copy(self.vec.as_ptr().add(idx),
1335 self.vec.as_mut_ptr().add(idx + amt),
1337 ptr::copy(bytes.as_ptr(),
1338 self.vec.as_mut_ptr().add(idx),
1340 self.vec.set_len(len + amt);
1343 /// Inserts a string slice into this `String` at a byte position.
1345 /// This is an `O(n)` operation as it requires copying every element in the
1350 /// Panics if `idx` is larger than the `String`'s length, or if it does not
1351 /// lie on a [`char`] boundary.
1353 /// [`char`]: ../../std/primitive.char.html
1360 /// let mut s = String::from("bar");
1362 /// s.insert_str(0, "foo");
1364 /// assert_eq!("foobar", s);
1367 #[stable(feature = "insert_str", since = "1.16.0")]
1368 pub fn insert_str(&mut self, idx: usize, string: &str) {
1369 assert!(self.is_char_boundary(idx));
1372 self.insert_bytes(idx, string.as_bytes());
1376 /// Returns a mutable reference to the contents of this `String`.
1380 /// This function is unsafe because it does not check that the bytes passed
1381 /// to it are valid UTF-8. If this constraint is violated, it may cause
1382 /// memory unsafety issues with future users of the `String`, as the rest of
1383 /// the standard library assumes that `String`s are valid UTF-8.
1390 /// let mut s = String::from("hello");
1393 /// let vec = s.as_mut_vec();
1394 /// assert_eq!(&[104, 101, 108, 108, 111][..], &vec[..]);
1398 /// assert_eq!(s, "olleh");
1401 #[stable(feature = "rust1", since = "1.0.0")]
1402 pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1406 /// Returns the length of this `String`, in bytes, not [`char`]s or
1407 /// graphemes. In other words, it may not be what a human considers the
1408 /// length of the string.
1415 /// let a = String::from("foo");
1416 /// assert_eq!(a.len(), 3);
1418 /// let fancy_f = String::from("ƒoo");
1419 /// assert_eq!(fancy_f.len(), 4);
1420 /// assert_eq!(fancy_f.chars().count(), 3);
1423 #[stable(feature = "rust1", since = "1.0.0")]
1424 pub fn len(&self) -> usize {
1428 /// Returns `true` if this `String` has a length of zero, and `false` otherwise.
1435 /// let mut v = String::new();
1436 /// assert!(v.is_empty());
1439 /// assert!(!v.is_empty());
1442 #[stable(feature = "rust1", since = "1.0.0")]
1443 pub fn is_empty(&self) -> bool {
1447 /// Splits the string into two at the given index.
1449 /// Returns a newly allocated `String`. `self` contains bytes `[0, at)`, and
1450 /// the returned `String` contains bytes `[at, len)`. `at` must be on the
1451 /// boundary of a UTF-8 code point.
1453 /// Note that the capacity of `self` does not change.
1457 /// Panics if `at` is not on a `UTF-8` code point boundary, or if it is beyond the last
1458 /// code point of the string.
1464 /// let mut hello = String::from("Hello, World!");
1465 /// let world = hello.split_off(7);
1466 /// assert_eq!(hello, "Hello, ");
1467 /// assert_eq!(world, "World!");
1471 #[stable(feature = "string_split_off", since = "1.16.0")]
1472 pub fn split_off(&mut self, at: usize) -> String {
1473 assert!(self.is_char_boundary(at));
1474 let other = self.vec.split_off(at);
1475 unsafe { String::from_utf8_unchecked(other) }
1478 /// Truncates this `String`, removing all contents.
1480 /// While this means the `String` will have a length of zero, it does not
1481 /// touch its capacity.
1488 /// let mut s = String::from("foo");
1492 /// assert!(s.is_empty());
1493 /// assert_eq!(0, s.len());
1494 /// assert_eq!(3, s.capacity());
1497 #[stable(feature = "rust1", since = "1.0.0")]
1498 pub fn clear(&mut self) {
1502 /// Creates a draining iterator that removes the specified range in the `String`
1503 /// and yields the removed `chars`.
1505 /// Note: The element range is removed even if the iterator is not
1506 /// consumed until the end.
1510 /// Panics if the starting point or end point do not lie on a [`char`]
1511 /// boundary, or if they're out of bounds.
1513 /// [`char`]: ../../std/primitive.char.html
1520 /// let mut s = String::from("α is alpha, β is beta");
1521 /// let beta_offset = s.find('β').unwrap_or(s.len());
1523 /// // Remove the range up until the β from the string
1524 /// let t: String = s.drain(..beta_offset).collect();
1525 /// assert_eq!(t, "α is alpha, ");
1526 /// assert_eq!(s, "β is beta");
1528 /// // A full range clears the string
1530 /// assert_eq!(s, "");
1532 #[stable(feature = "drain", since = "1.6.0")]
1533 pub fn drain<R>(&mut self, range: R) -> Drain<'_>
1534 where R: RangeBounds<usize>
1538 // The String version of Drain does not have the memory safety issues
1539 // of the vector version. The data is just plain bytes.
1540 // Because the range removal happens in Drop, if the Drain iterator is leaked,
1541 // the removal will not happen.
1542 let len = self.len();
1543 let start = match range.start_bound() {
1545 Excluded(&n) => n + 1,
1548 let end = match range.end_bound() {
1549 Included(&n) => n + 1,
1554 // Take out two simultaneous borrows. The &mut String won't be accessed
1555 // until iteration is over, in Drop.
1556 let self_ptr = self as *mut _;
1557 // slicing does the appropriate bounds checks
1558 let chars_iter = self[start..end].chars();
1568 /// Removes the specified range in the string,
1569 /// and replaces it with the given string.
1570 /// The given string doesn't need to be the same length as the range.
1574 /// Panics if the starting point or end point do not lie on a [`char`]
1575 /// boundary, or if they're out of bounds.
1577 /// [`char`]: ../../std/primitive.char.html
1578 /// [`Vec::splice`]: ../../std/vec/struct.Vec.html#method.splice
1585 /// let mut s = String::from("α is alpha, β is beta");
1586 /// let beta_offset = s.find('β').unwrap_or(s.len());
1588 /// // Replace the range up until the β from the string
1589 /// s.replace_range(..beta_offset, "Α is capital alpha; ");
1590 /// assert_eq!(s, "Α is capital alpha; β is beta");
1592 #[stable(feature = "splice", since = "1.27.0")]
1593 pub fn replace_range<R>(&mut self, range: R, replace_with: &str)
1594 where R: RangeBounds<usize>
1598 // Replace_range does not have the memory safety issues of a vector Splice.
1599 // of the vector version. The data is just plain bytes.
1601 match range.start_bound() {
1602 Included(&n) => assert!(self.is_char_boundary(n)),
1603 Excluded(&n) => assert!(self.is_char_boundary(n + 1)),
1606 match range.end_bound() {
1607 Included(&n) => assert!(self.is_char_boundary(n + 1)),
1608 Excluded(&n) => assert!(self.is_char_boundary(n)),
1614 }.splice(range, replace_with.bytes());
1617 /// Converts this `String` into a [`Box`]`<`[`str`]`>`.
1619 /// This will drop any excess capacity.
1621 /// [`Box`]: ../../std/boxed/struct.Box.html
1622 /// [`str`]: ../../std/primitive.str.html
1629 /// let s = String::from("hello");
1631 /// let b = s.into_boxed_str();
1633 #[stable(feature = "box_str", since = "1.4.0")]
1635 pub fn into_boxed_str(self) -> Box<str> {
1636 let slice = self.vec.into_boxed_slice();
1637 unsafe { from_boxed_utf8_unchecked(slice) }
1641 impl FromUtf8Error {
1642 /// Returns a slice of [`u8`]s bytes that were attempted to convert to a `String`.
1649 /// // some invalid bytes, in a vector
1650 /// let bytes = vec![0, 159];
1652 /// let value = String::from_utf8(bytes);
1654 /// assert_eq!(&[0, 159], value.unwrap_err().as_bytes());
1656 #[stable(feature = "from_utf8_error_as_bytes", since = "1.26.0")]
1657 pub fn as_bytes(&self) -> &[u8] {
1661 /// Returns the bytes that were attempted to convert to a `String`.
1663 /// This method is carefully constructed to avoid allocation. It will
1664 /// consume the error, moving out the bytes, so that a copy of the bytes
1665 /// does not need to be made.
1672 /// // some invalid bytes, in a vector
1673 /// let bytes = vec![0, 159];
1675 /// let value = String::from_utf8(bytes);
1677 /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
1679 #[stable(feature = "rust1", since = "1.0.0")]
1680 pub fn into_bytes(self) -> Vec<u8> {
1684 /// Fetch a `Utf8Error` to get more details about the conversion failure.
1686 /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
1687 /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
1688 /// an analogue to `FromUtf8Error`. See its documentation for more details
1691 /// [`Utf8Error`]: ../../std/str/struct.Utf8Error.html
1692 /// [`std::str`]: ../../std/str/index.html
1693 /// [`u8`]: ../../std/primitive.u8.html
1694 /// [`&str`]: ../../std/primitive.str.html
1701 /// // some invalid bytes, in a vector
1702 /// let bytes = vec![0, 159];
1704 /// let error = String::from_utf8(bytes).unwrap_err().utf8_error();
1706 /// // the first byte is invalid here
1707 /// assert_eq!(1, error.valid_up_to());
1709 #[stable(feature = "rust1", since = "1.0.0")]
1710 pub fn utf8_error(&self) -> Utf8Error {
1715 #[stable(feature = "rust1", since = "1.0.0")]
1716 impl fmt::Display for FromUtf8Error {
1717 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1718 fmt::Display::fmt(&self.error, f)
1722 #[stable(feature = "rust1", since = "1.0.0")]
1723 impl fmt::Display for FromUtf16Error {
1724 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1725 fmt::Display::fmt("invalid utf-16: lone surrogate found", f)
1729 #[stable(feature = "rust1", since = "1.0.0")]
1730 impl Clone for String {
1731 fn clone(&self) -> Self {
1732 String { vec: self.vec.clone() }
1735 fn clone_from(&mut self, source: &Self) {
1736 self.vec.clone_from(&source.vec);
1740 #[stable(feature = "rust1", since = "1.0.0")]
1741 impl FromIterator<char> for String {
1742 fn from_iter<I: IntoIterator<Item = char>>(iter: I) -> String {
1743 let mut buf = String::new();
1749 #[stable(feature = "string_from_iter_by_ref", since = "1.17.0")]
1750 impl<'a> FromIterator<&'a char> for String {
1751 fn from_iter<I: IntoIterator<Item = &'a char>>(iter: I) -> String {
1752 let mut buf = String::new();
1758 #[stable(feature = "rust1", since = "1.0.0")]
1759 impl<'a> FromIterator<&'a str> for String {
1760 fn from_iter<I: IntoIterator<Item = &'a str>>(iter: I) -> String {
1761 let mut buf = String::new();
1767 #[stable(feature = "extend_string", since = "1.4.0")]
1768 impl FromIterator<String> for String {
1769 fn from_iter<I: IntoIterator<Item = String>>(iter: I) -> String {
1770 let mut iterator = iter.into_iter();
1772 // Because we're iterating over `String`s, we can avoid at least
1773 // one allocation by getting the first string from the iterator
1774 // and appending to it all the subsequent strings.
1775 match iterator.next() {
1776 None => String::new(),
1778 buf.extend(iterator);
1785 #[stable(feature = "herd_cows", since = "1.19.0")]
1786 impl<'a> FromIterator<Cow<'a, str>> for String {
1787 fn from_iter<I: IntoIterator<Item = Cow<'a, str>>>(iter: I) -> String {
1788 let mut iterator = iter.into_iter();
1790 // Because we're iterating over CoWs, we can (potentially) avoid at least
1791 // one allocation by getting the first item and appending to it all the
1792 // subsequent items.
1793 match iterator.next() {
1794 None => String::new(),
1796 let mut buf = cow.into_owned();
1797 buf.extend(iterator);
1804 #[stable(feature = "rust1", since = "1.0.0")]
1805 impl Extend<char> for String {
1806 fn extend<I: IntoIterator<Item = char>>(&mut self, iter: I) {
1807 let iterator = iter.into_iter();
1808 let (lower_bound, _) = iterator.size_hint();
1809 self.reserve(lower_bound);
1810 iterator.for_each(move |c| self.push(c));
1814 #[stable(feature = "extend_ref", since = "1.2.0")]
1815 impl<'a> Extend<&'a char> for String {
1816 fn extend<I: IntoIterator<Item = &'a char>>(&mut self, iter: I) {
1817 self.extend(iter.into_iter().cloned());
1821 #[stable(feature = "rust1", since = "1.0.0")]
1822 impl<'a> Extend<&'a str> for String {
1823 fn extend<I: IntoIterator<Item = &'a str>>(&mut self, iter: I) {
1824 iter.into_iter().for_each(move |s| self.push_str(s));
1828 #[stable(feature = "extend_string", since = "1.4.0")]
1829 impl Extend<String> for String {
1830 fn extend<I: IntoIterator<Item = String>>(&mut self, iter: I) {
1831 iter.into_iter().for_each(move |s| self.push_str(&s));
1835 #[stable(feature = "herd_cows", since = "1.19.0")]
1836 impl<'a> Extend<Cow<'a, str>> for String {
1837 fn extend<I: IntoIterator<Item = Cow<'a, str>>>(&mut self, iter: I) {
1838 iter.into_iter().for_each(move |s| self.push_str(&s));
1842 /// A convenience impl that delegates to the impl for `&str`
1843 #[unstable(feature = "pattern",
1844 reason = "API not fully fleshed out and ready to be stabilized",
1846 impl<'a, 'b> Pattern<'a> for &'b String {
1847 type Searcher = <&'b str as Pattern<'a>>::Searcher;
1849 fn into_searcher(self, haystack: &'a str) -> <&'b str as Pattern<'a>>::Searcher {
1850 self[..].into_searcher(haystack)
1854 fn is_contained_in(self, haystack: &'a str) -> bool {
1855 self[..].is_contained_in(haystack)
1859 fn is_prefix_of(self, haystack: &'a str) -> bool {
1860 self[..].is_prefix_of(haystack)
1864 #[stable(feature = "rust1", since = "1.0.0")]
1865 impl PartialEq for String {
1867 fn eq(&self, other: &String) -> bool {
1868 PartialEq::eq(&self[..], &other[..])
1871 fn ne(&self, other: &String) -> bool {
1872 PartialEq::ne(&self[..], &other[..])
1876 macro_rules! impl_eq {
1877 ($lhs:ty, $rhs: ty) => {
1878 #[stable(feature = "rust1", since = "1.0.0")]
1879 #[allow(unused_lifetimes)]
1880 impl<'a, 'b> PartialEq<$rhs> for $lhs {
1882 fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
1884 fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
1887 #[stable(feature = "rust1", since = "1.0.0")]
1888 #[allow(unused_lifetimes)]
1889 impl<'a, 'b> PartialEq<$lhs> for $rhs {
1891 fn eq(&self, other: &$lhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
1893 fn ne(&self, other: &$lhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
1899 impl_eq! { String, str }
1900 impl_eq! { String, &'a str }
1901 impl_eq! { Cow<'a, str>, str }
1902 impl_eq! { Cow<'a, str>, &'b str }
1903 impl_eq! { Cow<'a, str>, String }
1905 #[stable(feature = "rust1", since = "1.0.0")]
1906 impl Default for String {
1907 /// Creates an empty `String`.
1909 fn default() -> String {
1914 #[stable(feature = "rust1", since = "1.0.0")]
1915 impl fmt::Display for String {
1917 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1918 fmt::Display::fmt(&**self, f)
1922 #[stable(feature = "rust1", since = "1.0.0")]
1923 impl fmt::Debug for String {
1925 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1926 fmt::Debug::fmt(&**self, f)
1930 #[stable(feature = "rust1", since = "1.0.0")]
1931 impl hash::Hash for String {
1933 fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
1934 (**self).hash(hasher)
1938 /// Implements the `+` operator for concatenating two strings.
1940 /// This consumes the `String` on the left-hand side and re-uses its buffer (growing it if
1941 /// necessary). This is done to avoid allocating a new `String` and copying the entire contents on
1942 /// every operation, which would lead to `O(n^2)` running time when building an `n`-byte string by
1943 /// repeated concatenation.
1945 /// The string on the right-hand side is only borrowed; its contents are copied into the returned
1950 /// Concatenating two `String`s takes the first by value and borrows the second:
1953 /// let a = String::from("hello");
1954 /// let b = String::from(" world");
1956 /// // `a` is moved and can no longer be used here.
1959 /// If you want to keep using the first `String`, you can clone it and append to the clone instead:
1962 /// let a = String::from("hello");
1963 /// let b = String::from(" world");
1964 /// let c = a.clone() + &b;
1965 /// // `a` is still valid here.
1968 /// Concatenating `&str` slices can be done by converting the first to a `String`:
1971 /// let a = "hello";
1972 /// let b = " world";
1973 /// let c = a.to_string() + b;
1975 #[stable(feature = "rust1", since = "1.0.0")]
1976 impl Add<&str> for String {
1977 type Output = String;
1980 fn add(mut self, other: &str) -> String {
1981 self.push_str(other);
1986 /// Implements the `+=` operator for appending to a `String`.
1988 /// This has the same behavior as the [`push_str`][String::push_str] method.
1989 #[stable(feature = "stringaddassign", since = "1.12.0")]
1990 impl AddAssign<&str> for String {
1992 fn add_assign(&mut self, other: &str) {
1993 self.push_str(other);
1997 #[stable(feature = "rust1", since = "1.0.0")]
1998 impl ops::Index<ops::Range<usize>> for String {
2002 fn index(&self, index: ops::Range<usize>) -> &str {
2006 #[stable(feature = "rust1", since = "1.0.0")]
2007 impl ops::Index<ops::RangeTo<usize>> for String {
2011 fn index(&self, index: ops::RangeTo<usize>) -> &str {
2015 #[stable(feature = "rust1", since = "1.0.0")]
2016 impl ops::Index<ops::RangeFrom<usize>> for String {
2020 fn index(&self, index: ops::RangeFrom<usize>) -> &str {
2024 #[stable(feature = "rust1", since = "1.0.0")]
2025 impl ops::Index<ops::RangeFull> for String {
2029 fn index(&self, _index: ops::RangeFull) -> &str {
2030 unsafe { str::from_utf8_unchecked(&self.vec) }
2033 #[stable(feature = "inclusive_range", since = "1.26.0")]
2034 impl ops::Index<ops::RangeInclusive<usize>> for String {
2038 fn index(&self, index: ops::RangeInclusive<usize>) -> &str {
2039 Index::index(&**self, index)
2042 #[stable(feature = "inclusive_range", since = "1.26.0")]
2043 impl ops::Index<ops::RangeToInclusive<usize>> for String {
2047 fn index(&self, index: ops::RangeToInclusive<usize>) -> &str {
2048 Index::index(&**self, index)
2052 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2053 impl ops::IndexMut<ops::Range<usize>> for String {
2055 fn index_mut(&mut self, index: ops::Range<usize>) -> &mut str {
2056 &mut self[..][index]
2059 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2060 impl ops::IndexMut<ops::RangeTo<usize>> for String {
2062 fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut str {
2063 &mut self[..][index]
2066 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2067 impl ops::IndexMut<ops::RangeFrom<usize>> for String {
2069 fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut str {
2070 &mut self[..][index]
2073 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2074 impl ops::IndexMut<ops::RangeFull> for String {
2076 fn index_mut(&mut self, _index: ops::RangeFull) -> &mut str {
2077 unsafe { str::from_utf8_unchecked_mut(&mut *self.vec) }
2080 #[stable(feature = "inclusive_range", since = "1.26.0")]
2081 impl ops::IndexMut<ops::RangeInclusive<usize>> for String {
2083 fn index_mut(&mut self, index: ops::RangeInclusive<usize>) -> &mut str {
2084 IndexMut::index_mut(&mut **self, index)
2087 #[stable(feature = "inclusive_range", since = "1.26.0")]
2088 impl ops::IndexMut<ops::RangeToInclusive<usize>> for String {
2090 fn index_mut(&mut self, index: ops::RangeToInclusive<usize>) -> &mut str {
2091 IndexMut::index_mut(&mut **self, index)
2095 #[stable(feature = "rust1", since = "1.0.0")]
2096 impl ops::Deref for String {
2100 fn deref(&self) -> &str {
2101 unsafe { str::from_utf8_unchecked(&self.vec) }
2105 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2106 impl ops::DerefMut for String {
2108 fn deref_mut(&mut self) -> &mut str {
2109 unsafe { str::from_utf8_unchecked_mut(&mut *self.vec) }
2113 /// An error when parsing a `String`.
2115 /// This `enum` is slightly awkward: it will never actually exist. This error is
2116 /// part of the type signature of the implementation of [`FromStr`] on
2117 /// [`String`]. The return type of [`from_str`], requires that an error be
2118 /// defined, but, given that a [`String`] can always be made into a new
2119 /// [`String`] without error, this type will never actually be returned. As
2120 /// such, it is only here to satisfy said signature, and is useless otherwise.
2122 /// [`FromStr`]: ../../std/str/trait.FromStr.html
2123 /// [`String`]: struct.String.html
2124 /// [`from_str`]: ../../std/str/trait.FromStr.html#tymethod.from_str
2125 #[stable(feature = "str_parse_error", since = "1.5.0")]
2126 pub type ParseError = core::convert::Infallible;
2128 #[stable(feature = "rust1", since = "1.0.0")]
2129 impl FromStr for String {
2130 type Err = core::convert::Infallible;
2132 fn from_str(s: &str) -> Result<String, ParseError> {
2138 /// A trait for converting a value to a `String`.
2140 /// This trait is automatically implemented for any type which implements the
2141 /// [`Display`] trait. As such, `ToString` shouldn't be implemented directly:
2142 /// [`Display`] should be implemented instead, and you get the `ToString`
2143 /// implementation for free.
2145 /// [`Display`]: ../../std/fmt/trait.Display.html
2146 #[stable(feature = "rust1", since = "1.0.0")]
2147 pub trait ToString {
2148 /// Converts the given value to a `String`.
2156 /// let five = String::from("5");
2158 /// assert_eq!(five, i.to_string());
2160 #[rustc_conversion_suggestion]
2161 #[stable(feature = "rust1", since = "1.0.0")]
2162 fn to_string(&self) -> String;
2167 /// In this implementation, the `to_string` method panics
2168 /// if the `Display` implementation returns an error.
2169 /// This indicates an incorrect `Display` implementation
2170 /// since `fmt::Write for String` never returns an error itself.
2171 #[stable(feature = "rust1", since = "1.0.0")]
2172 impl<T: fmt::Display + ?Sized> ToString for T {
2174 default fn to_string(&self) -> String {
2176 let mut buf = String::new();
2177 buf.write_fmt(format_args!("{}", self))
2178 .expect("a Display implementation returned an error unexpectedly");
2179 buf.shrink_to_fit();
2184 #[stable(feature = "str_to_string_specialization", since = "1.9.0")]
2185 impl ToString for str {
2187 fn to_string(&self) -> String {
2192 #[stable(feature = "cow_str_to_string_specialization", since = "1.17.0")]
2193 impl ToString for Cow<'_, str> {
2195 fn to_string(&self) -> String {
2200 #[stable(feature = "string_to_string_specialization", since = "1.17.0")]
2201 impl ToString for String {
2203 fn to_string(&self) -> String {
2208 #[stable(feature = "rust1", since = "1.0.0")]
2209 impl AsRef<str> for String {
2211 fn as_ref(&self) -> &str {
2216 #[stable(feature = "rust1", since = "1.0.0")]
2217 impl AsRef<[u8]> for String {
2219 fn as_ref(&self) -> &[u8] {
2224 #[stable(feature = "rust1", since = "1.0.0")]
2225 impl From<&str> for String {
2227 fn from(s: &str) -> String {
2232 #[stable(feature = "from_ref_string", since = "1.35.0")]
2233 impl From<&String> for String {
2235 fn from(s: &String) -> String {
2240 // note: test pulls in libstd, which causes errors here
2242 #[stable(feature = "string_from_box", since = "1.18.0")]
2243 impl From<Box<str>> for String {
2244 /// Converts the given boxed `str` slice to a `String`.
2245 /// It is notable that the `str` slice is owned.
2252 /// let s1: String = String::from("hello world");
2253 /// let s2: Box<str> = s1.into_boxed_str();
2254 /// let s3: String = String::from(s2);
2256 /// assert_eq!("hello world", s3)
2258 fn from(s: Box<str>) -> String {
2263 #[stable(feature = "box_from_str", since = "1.20.0")]
2264 impl From<String> for Box<str> {
2265 /// Converts the given `String` to a boxed `str` slice that is owned.
2272 /// let s1: String = String::from("hello world");
2273 /// let s2: Box<str> = Box::from(s1);
2274 /// let s3: String = String::from(s2);
2276 /// assert_eq!("hello world", s3)
2278 fn from(s: String) -> Box<str> {
2283 #[stable(feature = "string_from_cow_str", since = "1.14.0")]
2284 impl<'a> From<Cow<'a, str>> for String {
2285 fn from(s: Cow<'a, str>) -> String {
2290 #[stable(feature = "rust1", since = "1.0.0")]
2291 impl<'a> From<&'a str> for Cow<'a, str> {
2293 fn from(s: &'a str) -> Cow<'a, str> {
2298 #[stable(feature = "rust1", since = "1.0.0")]
2299 impl<'a> From<String> for Cow<'a, str> {
2301 fn from(s: String) -> Cow<'a, str> {
2306 #[stable(feature = "cow_from_string_ref", since = "1.28.0")]
2307 impl<'a> From<&'a String> for Cow<'a, str> {
2309 fn from(s: &'a String) -> Cow<'a, str> {
2310 Cow::Borrowed(s.as_str())
2314 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2315 impl<'a> FromIterator<char> for Cow<'a, str> {
2316 fn from_iter<I: IntoIterator<Item = char>>(it: I) -> Cow<'a, str> {
2317 Cow::Owned(FromIterator::from_iter(it))
2321 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2322 impl<'a, 'b> FromIterator<&'b str> for Cow<'a, str> {
2323 fn from_iter<I: IntoIterator<Item = &'b str>>(it: I) -> Cow<'a, str> {
2324 Cow::Owned(FromIterator::from_iter(it))
2328 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2329 impl<'a> FromIterator<String> for Cow<'a, str> {
2330 fn from_iter<I: IntoIterator<Item = String>>(it: I) -> Cow<'a, str> {
2331 Cow::Owned(FromIterator::from_iter(it))
2335 #[stable(feature = "from_string_for_vec_u8", since = "1.14.0")]
2336 impl From<String> for Vec<u8> {
2337 /// Converts the given `String` to a vector `Vec` that holds values of type `u8`.
2344 /// let s1 = String::from("hello world");
2345 /// let v1 = Vec::from(s1);
2348 /// println!("{}", b);
2351 fn from(string: String) -> Vec<u8> {
2356 #[stable(feature = "rust1", since = "1.0.0")]
2357 impl fmt::Write for String {
2359 fn write_str(&mut self, s: &str) -> fmt::Result {
2365 fn write_char(&mut self, c: char) -> fmt::Result {
2371 /// A draining iterator for `String`.
2373 /// This struct is created by the [`drain`] method on [`String`]. See its
2374 /// documentation for more.
2376 /// [`drain`]: struct.String.html#method.drain
2377 /// [`String`]: struct.String.html
2378 #[stable(feature = "drain", since = "1.6.0")]
2379 pub struct Drain<'a> {
2380 /// Will be used as &'a mut String in the destructor
2381 string: *mut String,
2382 /// Start of part to remove
2384 /// End of part to remove
2386 /// Current remaining range to remove
2390 #[stable(feature = "collection_debug", since = "1.17.0")]
2391 impl fmt::Debug for Drain<'_> {
2392 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2393 f.pad("Drain { .. }")
2397 #[stable(feature = "drain", since = "1.6.0")]
2398 unsafe impl Sync for Drain<'_> {}
2399 #[stable(feature = "drain", since = "1.6.0")]
2400 unsafe impl Send for Drain<'_> {}
2402 #[stable(feature = "drain", since = "1.6.0")]
2403 impl Drop for Drain<'_> {
2404 fn drop(&mut self) {
2406 // Use Vec::drain. "Reaffirm" the bounds checks to avoid
2407 // panic code being inserted again.
2408 let self_vec = (*self.string).as_mut_vec();
2409 if self.start <= self.end && self.end <= self_vec.len() {
2410 self_vec.drain(self.start..self.end);
2416 #[stable(feature = "drain", since = "1.6.0")]
2417 impl Iterator for Drain<'_> {
2421 fn next(&mut self) -> Option<char> {
2425 fn size_hint(&self) -> (usize, Option<usize>) {
2426 self.iter.size_hint()
2430 fn last(mut self) -> Option<char> {
2435 #[stable(feature = "drain", since = "1.6.0")]
2436 impl DoubleEndedIterator for Drain<'_> {
2438 fn next_back(&mut self) -> Option<char> {
2439 self.iter.next_back()
2443 #[stable(feature = "fused", since = "1.26.0")]
2444 impl FusedIterator for Drain<'_> {}