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 /// let ptr = story.as_ptr();
200 /// let len = story.len();
201 /// let capacity = story.capacity();
203 /// // story has nineteen bytes
204 /// assert_eq!(19, len);
206 /// // Now that we have our parts, we throw the story away.
207 /// mem::forget(story);
209 /// // We can re-build a String out of ptr, len, and capacity. This is all
210 /// // unsafe because we are responsible for making sure the components are
212 /// let s = unsafe { String::from_raw_parts(ptr as *mut _, len, capacity) } ;
214 /// assert_eq!(String::from("Once upon a time..."), s);
217 /// [`as_ptr`]: #method.as_ptr
218 /// [`len`]: #method.len
219 /// [`capacity`]: #method.capacity
221 /// If a `String` has enough capacity, adding elements to it will not
222 /// re-allocate. For example, consider this program:
225 /// let mut s = String::new();
227 /// println!("{}", s.capacity());
230 /// s.push_str("hello");
231 /// println!("{}", s.capacity());
235 /// This will output the following:
246 /// At first, we have no memory allocated at all, but as we append to the
247 /// string, it increases its capacity appropriately. If we instead use the
248 /// [`with_capacity`] method to allocate the correct capacity initially:
251 /// let mut s = String::with_capacity(25);
253 /// println!("{}", s.capacity());
256 /// s.push_str("hello");
257 /// println!("{}", s.capacity());
261 /// [`with_capacity`]: #method.with_capacity
263 /// We end up with a different output:
274 /// Here, there's no need to allocate more memory inside the loop.
276 /// [`&str`]: ../../std/primitive.str.html
277 /// [`Deref`]: ../../std/ops/trait.Deref.html
278 /// [`as_str()`]: struct.String.html#method.as_str
279 #[derive(PartialOrd, Eq, Ord)]
280 #[stable(feature = "rust1", since = "1.0.0")]
285 /// A possible error value when converting a `String` from a UTF-8 byte vector.
287 /// This type is the error type for the [`from_utf8`] method on [`String`]. It
288 /// is designed in such a way to carefully avoid reallocations: the
289 /// [`into_bytes`] method will give back the byte vector that was used in the
290 /// conversion attempt.
292 /// [`from_utf8`]: struct.String.html#method.from_utf8
293 /// [`String`]: struct.String.html
294 /// [`into_bytes`]: struct.FromUtf8Error.html#method.into_bytes
296 /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
297 /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
298 /// an analogue to `FromUtf8Error`, and you can get one from a `FromUtf8Error`
299 /// through the [`utf8_error`] method.
301 /// [`Utf8Error`]: ../../std/str/struct.Utf8Error.html
302 /// [`std::str`]: ../../std/str/index.html
303 /// [`u8`]: ../../std/primitive.u8.html
304 /// [`&str`]: ../../std/primitive.str.html
305 /// [`utf8_error`]: #method.utf8_error
312 /// // some invalid bytes, in a vector
313 /// let bytes = vec![0, 159];
315 /// let value = String::from_utf8(bytes);
317 /// assert!(value.is_err());
318 /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
320 #[stable(feature = "rust1", since = "1.0.0")]
322 pub struct FromUtf8Error {
327 /// A possible error value when converting a `String` from a UTF-16 byte slice.
329 /// This type is the error type for the [`from_utf16`] method on [`String`].
331 /// [`from_utf16`]: struct.String.html#method.from_utf16
332 /// [`String`]: struct.String.html
339 /// // 𝄞mu<invalid>ic
340 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
341 /// 0xD800, 0x0069, 0x0063];
343 /// assert!(String::from_utf16(v).is_err());
345 #[stable(feature = "rust1", since = "1.0.0")]
347 pub struct FromUtf16Error(());
350 /// Creates a new empty `String`.
352 /// Given that the `String` is empty, this will not allocate any initial
353 /// buffer. While that means that this initial operation is very
354 /// inexpensive, it may cause excessive allocation later when you add
355 /// data. If you have an idea of how much data the `String` will hold,
356 /// consider the [`with_capacity`] method to prevent excessive
359 /// [`with_capacity`]: #method.with_capacity
366 /// let s = String::new();
369 #[stable(feature = "rust1", since = "1.0.0")]
370 pub const fn new() -> String {
371 String { vec: Vec::new() }
374 /// Creates a new empty `String` with a particular capacity.
376 /// `String`s have an internal buffer to hold their data. The capacity is
377 /// the length of that buffer, and can be queried with the [`capacity`]
378 /// method. This method creates an empty `String`, but one with an initial
379 /// buffer that can hold `capacity` bytes. This is useful when you may be
380 /// appending a bunch of data to the `String`, reducing the number of
381 /// reallocations it needs to do.
383 /// [`capacity`]: #method.capacity
385 /// If the given capacity is `0`, no allocation will occur, and this method
386 /// is identical to the [`new`] method.
388 /// [`new`]: #method.new
395 /// let mut s = String::with_capacity(10);
397 /// // The String contains no chars, even though it has capacity for more
398 /// assert_eq!(s.len(), 0);
400 /// // These are all done without reallocating...
401 /// let cap = s.capacity();
406 /// assert_eq!(s.capacity(), cap);
408 /// // ...but this may make the vector reallocate
412 #[stable(feature = "rust1", since = "1.0.0")]
413 pub fn with_capacity(capacity: usize) -> String {
414 String { vec: Vec::with_capacity(capacity) }
417 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
418 // required for this method definition, is not available. Since we don't
419 // require this method for testing purposes, I'll just stub it
420 // NB see the slice::hack module in slice.rs for more information
423 pub fn from_str(_: &str) -> String {
424 panic!("not available with cfg(test)");
427 /// Converts a vector of bytes to a `String`.
429 /// A string ([`String`]) is made of bytes ([`u8`]), and a vector of bytes
430 /// ([`Vec<u8>`]) is made of bytes, so this function converts between the
431 /// two. Not all byte slices are valid `String`s, however: `String`
432 /// requires that it is valid UTF-8. `from_utf8()` checks to ensure that
433 /// the bytes are valid UTF-8, and then does the conversion.
435 /// If you are sure that the byte slice is valid UTF-8, and you don't want
436 /// to incur the overhead of the validity check, there is an unsafe version
437 /// of this function, [`from_utf8_unchecked`], which has the same behavior
438 /// but skips the check.
440 /// This method will take care to not copy the vector, for efficiency's
443 /// If you need a [`&str`] instead of a `String`, consider
444 /// [`str::from_utf8`].
446 /// The inverse of this method is [`into_bytes`].
450 /// Returns [`Err`] if the slice is not UTF-8 with a description as to why the
451 /// provided bytes are not UTF-8. The vector you moved in is also included.
458 /// // some bytes, in a vector
459 /// let sparkle_heart = vec![240, 159, 146, 150];
461 /// // We know these bytes are valid, so we'll use `unwrap()`.
462 /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
464 /// assert_eq!("💖", sparkle_heart);
470 /// // some invalid bytes, in a vector
471 /// let sparkle_heart = vec![0, 159, 146, 150];
473 /// assert!(String::from_utf8(sparkle_heart).is_err());
476 /// See the docs for [`FromUtf8Error`] for more details on what you can do
479 /// [`from_utf8_unchecked`]: struct.String.html#method.from_utf8_unchecked
480 /// [`String`]: struct.String.html
481 /// [`u8`]: ../../std/primitive.u8.html
482 /// [`Vec<u8>`]: ../../std/vec/struct.Vec.html
483 /// [`str::from_utf8`]: ../../std/str/fn.from_utf8.html
484 /// [`into_bytes`]: struct.String.html#method.into_bytes
485 /// [`FromUtf8Error`]: struct.FromUtf8Error.html
486 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
488 #[stable(feature = "rust1", since = "1.0.0")]
489 pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error> {
490 match str::from_utf8(&vec) {
491 Ok(..) => Ok(String { vec }),
501 /// Converts a slice of bytes to a string, including invalid characters.
503 /// Strings are made of bytes ([`u8`]), and a slice of bytes
504 /// ([`&[u8]`][byteslice]) is made of bytes, so this function converts
505 /// between the two. Not all byte slices are valid strings, however: strings
506 /// are required to be valid UTF-8. During this conversion,
507 /// `from_utf8_lossy()` will replace any invalid UTF-8 sequences with
508 /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD], which looks like this: �
510 /// [`u8`]: ../../std/primitive.u8.html
511 /// [byteslice]: ../../std/primitive.slice.html
512 /// [U+FFFD]: ../char/constant.REPLACEMENT_CHARACTER.html
514 /// If you are sure that the byte slice is valid UTF-8, and you don't want
515 /// to incur the overhead of the conversion, there is an unsafe version
516 /// of this function, [`from_utf8_unchecked`], which has the same behavior
517 /// but skips the checks.
519 /// [`from_utf8_unchecked`]: struct.String.html#method.from_utf8_unchecked
521 /// This function returns a [`Cow<'a, str>`]. If our byte slice is invalid
522 /// UTF-8, then we need to insert the replacement characters, which will
523 /// change the size of the string, and hence, require a `String`. But if
524 /// it's already valid UTF-8, we don't need a new allocation. This return
525 /// type allows us to handle both cases.
527 /// [`Cow<'a, str>`]: ../../std/borrow/enum.Cow.html
534 /// // some bytes, in a vector
535 /// let sparkle_heart = vec![240, 159, 146, 150];
537 /// let sparkle_heart = String::from_utf8_lossy(&sparkle_heart);
539 /// assert_eq!("💖", sparkle_heart);
545 /// // some invalid bytes
546 /// let input = b"Hello \xF0\x90\x80World";
547 /// let output = String::from_utf8_lossy(input);
549 /// assert_eq!("Hello �World", output);
551 #[stable(feature = "rust1", since = "1.0.0")]
552 pub fn from_utf8_lossy(v: &[u8]) -> Cow<'_, str> {
553 let mut iter = lossy::Utf8Lossy::from_bytes(v).chunks();
555 let (first_valid, first_broken) = if let Some(chunk) = iter.next() {
556 let lossy::Utf8LossyChunk { valid, broken } = chunk;
557 if valid.len() == v.len() {
558 debug_assert!(broken.is_empty());
559 return Cow::Borrowed(valid);
563 return Cow::Borrowed("");
566 const REPLACEMENT: &str = "\u{FFFD}";
568 let mut res = String::with_capacity(v.len());
569 res.push_str(first_valid);
570 if !first_broken.is_empty() {
571 res.push_str(REPLACEMENT);
574 for lossy::Utf8LossyChunk { valid, broken } in iter {
576 if !broken.is_empty() {
577 res.push_str(REPLACEMENT);
584 /// Decode a UTF-16 encoded vector `v` into a `String`, returning [`Err`]
585 /// if `v` contains any invalid data.
587 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
595 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
596 /// 0x0073, 0x0069, 0x0063];
597 /// assert_eq!(String::from("𝄞music"),
598 /// String::from_utf16(v).unwrap());
600 /// // 𝄞mu<invalid>ic
601 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
602 /// 0xD800, 0x0069, 0x0063];
603 /// assert!(String::from_utf16(v).is_err());
605 #[stable(feature = "rust1", since = "1.0.0")]
606 pub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error> {
607 // This isn't done via collect::<Result<_, _>>() for performance reasons.
608 // FIXME: the function can be simplified again when #48994 is closed.
609 let mut ret = String::with_capacity(v.len());
610 for c in decode_utf16(v.iter().cloned()) {
614 return Err(FromUtf16Error(()));
620 /// Decode a UTF-16 encoded slice `v` into a `String`, replacing
621 /// invalid data with [the replacement character (`U+FFFD`)][U+FFFD].
623 /// Unlike [`from_utf8_lossy`] which returns a [`Cow<'a, str>`],
624 /// `from_utf16_lossy` returns a `String` since the UTF-16 to UTF-8
625 /// conversion requires a memory allocation.
627 /// [`from_utf8_lossy`]: #method.from_utf8_lossy
628 /// [`Cow<'a, str>`]: ../borrow/enum.Cow.html
629 /// [U+FFFD]: ../char/constant.REPLACEMENT_CHARACTER.html
636 /// // 𝄞mus<invalid>ic<invalid>
637 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
638 /// 0x0073, 0xDD1E, 0x0069, 0x0063,
641 /// assert_eq!(String::from("𝄞mus\u{FFFD}ic\u{FFFD}"),
642 /// String::from_utf16_lossy(v));
645 #[stable(feature = "rust1", since = "1.0.0")]
646 pub fn from_utf16_lossy(v: &[u16]) -> String {
647 decode_utf16(v.iter().cloned()).map(|r| r.unwrap_or(REPLACEMENT_CHARACTER)).collect()
650 /// Creates a new `String` from a length, capacity, and pointer.
654 /// This is highly unsafe, due to the number of invariants that aren't
657 /// * The memory at `ptr` needs to have been previously allocated by the
658 /// same allocator the standard library uses.
659 /// * `length` needs to be less than or equal to `capacity`.
660 /// * `capacity` needs to be the correct value.
662 /// Violating these may cause problems like corrupting the allocator's
663 /// internal data structures.
665 /// The ownership of `ptr` is effectively transferred to the
666 /// `String` which may then deallocate, reallocate or change the
667 /// contents of memory pointed to by the pointer at will. Ensure
668 /// that nothing else uses the pointer after calling this
679 /// let s = String::from("hello");
680 /// let ptr = s.as_ptr();
681 /// let len = s.len();
682 /// let capacity = s.capacity();
686 /// let s = String::from_raw_parts(ptr as *mut _, len, capacity);
688 /// assert_eq!(String::from("hello"), s);
692 #[stable(feature = "rust1", since = "1.0.0")]
693 pub unsafe fn from_raw_parts(buf: *mut u8, length: usize, capacity: usize) -> String {
694 String { vec: Vec::from_raw_parts(buf, length, capacity) }
697 /// Converts a vector of bytes to a `String` without checking that the
698 /// string contains valid UTF-8.
700 /// See the safe version, [`from_utf8`], for more details.
702 /// [`from_utf8`]: struct.String.html#method.from_utf8
706 /// This function is unsafe because it does not check that the bytes passed
707 /// to it are valid UTF-8. If this constraint is violated, it may cause
708 /// memory unsafety issues with future users of the `String`, as the rest of
709 /// the standard library assumes that `String`s are valid UTF-8.
716 /// // some bytes, in a vector
717 /// let sparkle_heart = vec![240, 159, 146, 150];
719 /// let sparkle_heart = unsafe {
720 /// String::from_utf8_unchecked(sparkle_heart)
723 /// assert_eq!("💖", sparkle_heart);
726 #[stable(feature = "rust1", since = "1.0.0")]
727 pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String {
728 String { vec: bytes }
731 /// Converts a `String` into a byte vector.
733 /// This consumes the `String`, so we do not need to copy its contents.
740 /// let s = String::from("hello");
741 /// let bytes = s.into_bytes();
743 /// assert_eq!(&[104, 101, 108, 108, 111][..], &bytes[..]);
746 #[stable(feature = "rust1", since = "1.0.0")]
747 pub fn into_bytes(self) -> Vec<u8> {
751 /// Extracts a string slice containing the entire `String`.
758 /// let s = String::from("foo");
760 /// assert_eq!("foo", s.as_str());
763 #[stable(feature = "string_as_str", since = "1.7.0")]
764 pub fn as_str(&self) -> &str {
768 /// Converts a `String` into a mutable string slice.
775 /// let mut s = String::from("foobar");
776 /// let s_mut_str = s.as_mut_str();
778 /// s_mut_str.make_ascii_uppercase();
780 /// assert_eq!("FOOBAR", s_mut_str);
783 #[stable(feature = "string_as_str", since = "1.7.0")]
784 pub fn as_mut_str(&mut self) -> &mut str {
788 /// Appends a given string slice onto the end of this `String`.
795 /// let mut s = String::from("foo");
797 /// s.push_str("bar");
799 /// assert_eq!("foobar", s);
802 #[stable(feature = "rust1", since = "1.0.0")]
803 pub fn push_str(&mut self, string: &str) {
804 self.vec.extend_from_slice(string.as_bytes())
807 /// Returns this `String`'s capacity, in bytes.
814 /// let s = String::with_capacity(10);
816 /// assert!(s.capacity() >= 10);
819 #[stable(feature = "rust1", since = "1.0.0")]
820 pub fn capacity(&self) -> usize {
824 /// Ensures that this `String`'s capacity is at least `additional` bytes
825 /// larger than its length.
827 /// The capacity may be increased by more than `additional` bytes if it
828 /// chooses, to prevent frequent reallocations.
830 /// If you do not want this "at least" behavior, see the [`reserve_exact`]
835 /// Panics if the new capacity overflows [`usize`].
837 /// [`reserve_exact`]: struct.String.html#method.reserve_exact
838 /// [`usize`]: ../../std/primitive.usize.html
845 /// let mut s = String::new();
849 /// assert!(s.capacity() >= 10);
852 /// This may not actually increase the capacity:
855 /// let mut s = String::with_capacity(10);
859 /// // s now has a length of 2 and a capacity of 10
860 /// assert_eq!(2, s.len());
861 /// assert_eq!(10, s.capacity());
863 /// // Since we already have an extra 8 capacity, calling this...
866 /// // ... doesn't actually increase.
867 /// assert_eq!(10, s.capacity());
870 #[stable(feature = "rust1", since = "1.0.0")]
871 pub fn reserve(&mut self, additional: usize) {
872 self.vec.reserve(additional)
875 /// Ensures that this `String`'s capacity is `additional` bytes
876 /// larger than its length.
878 /// Consider using the [`reserve`] method unless you absolutely know
879 /// better than the allocator.
881 /// [`reserve`]: #method.reserve
885 /// Panics if the new capacity overflows `usize`.
892 /// let mut s = String::new();
894 /// s.reserve_exact(10);
896 /// assert!(s.capacity() >= 10);
899 /// This may not actually increase the capacity:
902 /// let mut s = String::with_capacity(10);
906 /// // s now has a length of 2 and a capacity of 10
907 /// assert_eq!(2, s.len());
908 /// assert_eq!(10, s.capacity());
910 /// // Since we already have an extra 8 capacity, calling this...
911 /// s.reserve_exact(8);
913 /// // ... doesn't actually increase.
914 /// assert_eq!(10, s.capacity());
917 #[stable(feature = "rust1", since = "1.0.0")]
918 pub fn reserve_exact(&mut self, additional: usize) {
919 self.vec.reserve_exact(additional)
922 /// Tries to reserve capacity for at least `additional` more elements to be inserted
923 /// in the given `String`. The collection may reserve more space to avoid
924 /// frequent reallocations. After calling `reserve`, capacity will be
925 /// greater than or equal to `self.len() + additional`. Does nothing if
926 /// capacity is already sufficient.
930 /// If the capacity overflows, or the allocator reports a failure, then an error
936 /// #![feature(try_reserve)]
937 /// use std::collections::TryReserveError;
939 /// fn process_data(data: &str) -> Result<String, TryReserveError> {
940 /// let mut output = String::new();
942 /// // Pre-reserve the memory, exiting if we can't
943 /// output.try_reserve(data.len())?;
945 /// // Now we know this can't OOM in the middle of our complex work
946 /// output.push_str(data);
950 /// # process_data("rust").expect("why is the test harness OOMing on 4 bytes?");
952 #[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
953 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
954 self.vec.try_reserve(additional)
957 /// Tries to reserves the minimum capacity for exactly `additional` more elements to
958 /// be inserted in the given `String`. After calling `reserve_exact`,
959 /// capacity will be greater than or equal to `self.len() + additional`.
960 /// Does nothing if the capacity is already sufficient.
962 /// Note that the allocator may give the collection more space than it
963 /// requests. Therefore, capacity can not be relied upon to be precisely
964 /// minimal. Prefer `reserve` if future insertions are expected.
968 /// If the capacity overflows, or the allocator reports a failure, then an error
974 /// #![feature(try_reserve)]
975 /// use std::collections::TryReserveError;
977 /// fn process_data(data: &str) -> Result<String, TryReserveError> {
978 /// let mut output = String::new();
980 /// // Pre-reserve the memory, exiting if we can't
981 /// output.try_reserve(data.len())?;
983 /// // Now we know this can't OOM in the middle of our complex work
984 /// output.push_str(data);
988 /// # process_data("rust").expect("why is the test harness OOMing on 4 bytes?");
990 #[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
991 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
992 self.vec.try_reserve_exact(additional)
995 /// Shrinks the capacity of this `String` to match its length.
1002 /// let mut s = String::from("foo");
1005 /// assert!(s.capacity() >= 100);
1007 /// s.shrink_to_fit();
1008 /// assert_eq!(3, s.capacity());
1011 #[stable(feature = "rust1", since = "1.0.0")]
1012 pub fn shrink_to_fit(&mut self) {
1013 self.vec.shrink_to_fit()
1016 /// Shrinks the capacity of this `String` with a lower bound.
1018 /// The capacity will remain at least as large as both the length
1019 /// and the supplied value.
1021 /// Panics if the current capacity is smaller than the supplied
1022 /// minimum capacity.
1027 /// #![feature(shrink_to)]
1028 /// let mut s = String::from("foo");
1031 /// assert!(s.capacity() >= 100);
1033 /// s.shrink_to(10);
1034 /// assert!(s.capacity() >= 10);
1036 /// assert!(s.capacity() >= 3);
1039 #[unstable(feature = "shrink_to", reason = "new API", issue="56431")]
1040 pub fn shrink_to(&mut self, min_capacity: usize) {
1041 self.vec.shrink_to(min_capacity)
1044 /// Appends the given [`char`] to the end of this `String`.
1046 /// [`char`]: ../../std/primitive.char.html
1053 /// let mut s = String::from("abc");
1059 /// assert_eq!("abc123", s);
1062 #[stable(feature = "rust1", since = "1.0.0")]
1063 pub fn push(&mut self, ch: char) {
1064 match ch.len_utf8() {
1065 1 => self.vec.push(ch as u8),
1066 _ => self.vec.extend_from_slice(ch.encode_utf8(&mut [0; 4]).as_bytes()),
1070 /// Returns a byte slice of this `String`'s contents.
1072 /// The inverse of this method is [`from_utf8`].
1074 /// [`from_utf8`]: #method.from_utf8
1081 /// let s = String::from("hello");
1083 /// assert_eq!(&[104, 101, 108, 108, 111], s.as_bytes());
1086 #[stable(feature = "rust1", since = "1.0.0")]
1087 pub fn as_bytes(&self) -> &[u8] {
1091 /// Shortens this `String` to the specified length.
1093 /// If `new_len` is greater than the string's current length, this has no
1096 /// Note that this method has no effect on the allocated capacity
1101 /// Panics if `new_len` does not lie on a [`char`] boundary.
1103 /// [`char`]: ../../std/primitive.char.html
1110 /// let mut s = String::from("hello");
1114 /// assert_eq!("he", s);
1117 #[stable(feature = "rust1", since = "1.0.0")]
1118 pub fn truncate(&mut self, new_len: usize) {
1119 if new_len <= self.len() {
1120 assert!(self.is_char_boundary(new_len));
1121 self.vec.truncate(new_len)
1125 /// Removes the last character from the string buffer and returns it.
1127 /// Returns [`None`] if this `String` is empty.
1129 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1136 /// let mut s = String::from("foo");
1138 /// assert_eq!(s.pop(), Some('o'));
1139 /// assert_eq!(s.pop(), Some('o'));
1140 /// assert_eq!(s.pop(), Some('f'));
1142 /// assert_eq!(s.pop(), None);
1145 #[stable(feature = "rust1", since = "1.0.0")]
1146 pub fn pop(&mut self) -> Option<char> {
1147 let ch = self.chars().rev().next()?;
1148 let newlen = self.len() - ch.len_utf8();
1150 self.vec.set_len(newlen);
1155 /// Removes a [`char`] from this `String` at a byte position and returns it.
1157 /// This is an `O(n)` operation, as it requires copying every element in the
1162 /// Panics if `idx` is larger than or equal to the `String`'s length,
1163 /// or if it does not lie on a [`char`] boundary.
1165 /// [`char`]: ../../std/primitive.char.html
1172 /// let mut s = String::from("foo");
1174 /// assert_eq!(s.remove(0), 'f');
1175 /// assert_eq!(s.remove(1), 'o');
1176 /// assert_eq!(s.remove(0), 'o');
1179 #[stable(feature = "rust1", since = "1.0.0")]
1180 pub fn remove(&mut self, idx: usize) -> char {
1181 let ch = match self[idx..].chars().next() {
1183 None => panic!("cannot remove a char from the end of a string"),
1186 let next = idx + ch.len_utf8();
1187 let len = self.len();
1189 ptr::copy(self.vec.as_ptr().add(next),
1190 self.vec.as_mut_ptr().add(idx),
1192 self.vec.set_len(len - (next - idx));
1197 /// Retains only the characters specified by the predicate.
1199 /// In other words, remove all characters `c` such that `f(c)` returns `false`.
1200 /// This method operates in place, visiting each character exactly once in the
1201 /// original order, and preserves the order of the retained characters.
1206 /// let mut s = String::from("f_o_ob_ar");
1208 /// s.retain(|c| c != '_');
1210 /// assert_eq!(s, "foobar");
1213 /// The exact order may be useful for tracking external state, like an index.
1216 /// let mut s = String::from("abcde");
1217 /// let keep = [false, true, true, false, true];
1219 /// s.retain(|_| (keep[i], i += 1).0);
1220 /// assert_eq!(s, "bce");
1223 #[stable(feature = "string_retain", since = "1.26.0")]
1224 pub fn retain<F>(&mut self, mut f: F)
1225 where F: FnMut(char) -> bool
1227 let len = self.len();
1228 let mut del_bytes = 0;
1233 self.get_unchecked(idx..len).chars().next().unwrap()
1235 let ch_len = ch.len_utf8();
1238 del_bytes += ch_len;
1239 } else if del_bytes > 0 {
1241 ptr::copy(self.vec.as_ptr().add(idx),
1242 self.vec.as_mut_ptr().add(idx - del_bytes),
1247 // Point idx to the next char
1252 unsafe { self.vec.set_len(len - del_bytes); }
1256 /// Inserts a character into this `String` at a byte position.
1258 /// This is an `O(n)` operation as it requires copying every element in the
1263 /// Panics if `idx` is larger than the `String`'s length, or if it does not
1264 /// lie on a [`char`] boundary.
1266 /// [`char`]: ../../std/primitive.char.html
1273 /// let mut s = String::with_capacity(3);
1275 /// s.insert(0, 'f');
1276 /// s.insert(1, 'o');
1277 /// s.insert(2, 'o');
1279 /// assert_eq!("foo", s);
1282 #[stable(feature = "rust1", since = "1.0.0")]
1283 pub fn insert(&mut self, idx: usize, ch: char) {
1284 assert!(self.is_char_boundary(idx));
1285 let mut bits = [0; 4];
1286 let bits = ch.encode_utf8(&mut bits).as_bytes();
1289 self.insert_bytes(idx, bits);
1293 unsafe fn insert_bytes(&mut self, idx: usize, bytes: &[u8]) {
1294 let len = self.len();
1295 let amt = bytes.len();
1296 self.vec.reserve(amt);
1298 ptr::copy(self.vec.as_ptr().add(idx),
1299 self.vec.as_mut_ptr().add(idx + amt),
1301 ptr::copy(bytes.as_ptr(),
1302 self.vec.as_mut_ptr().add(idx),
1304 self.vec.set_len(len + amt);
1307 /// Inserts a string slice into this `String` at a byte position.
1309 /// This is an `O(n)` operation as it requires copying every element in the
1314 /// Panics if `idx` is larger than the `String`'s length, or if it does not
1315 /// lie on a [`char`] boundary.
1317 /// [`char`]: ../../std/primitive.char.html
1324 /// let mut s = String::from("bar");
1326 /// s.insert_str(0, "foo");
1328 /// assert_eq!("foobar", s);
1331 #[stable(feature = "insert_str", since = "1.16.0")]
1332 pub fn insert_str(&mut self, idx: usize, string: &str) {
1333 assert!(self.is_char_boundary(idx));
1336 self.insert_bytes(idx, string.as_bytes());
1340 /// Returns a mutable reference to the contents of this `String`.
1344 /// This function is unsafe because it does not check that the bytes passed
1345 /// to it are valid UTF-8. If this constraint is violated, it may cause
1346 /// memory unsafety issues with future users of the `String`, as the rest of
1347 /// the standard library assumes that `String`s are valid UTF-8.
1354 /// let mut s = String::from("hello");
1357 /// let vec = s.as_mut_vec();
1358 /// assert_eq!(&[104, 101, 108, 108, 111][..], &vec[..]);
1362 /// assert_eq!(s, "olleh");
1365 #[stable(feature = "rust1", since = "1.0.0")]
1366 pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1370 /// Returns the length of this `String`, in bytes.
1377 /// let a = String::from("foo");
1379 /// assert_eq!(a.len(), 3);
1382 #[stable(feature = "rust1", since = "1.0.0")]
1383 pub fn len(&self) -> usize {
1387 /// Returns `true` if this `String` has a length of zero, and `false` otherwise.
1394 /// let mut v = String::new();
1395 /// assert!(v.is_empty());
1398 /// assert!(!v.is_empty());
1401 #[stable(feature = "rust1", since = "1.0.0")]
1402 pub fn is_empty(&self) -> bool {
1406 /// Splits the string into two at the given index.
1408 /// Returns a newly allocated `String`. `self` contains bytes `[0, at)`, and
1409 /// the returned `String` contains bytes `[at, len)`. `at` must be on the
1410 /// boundary of a UTF-8 code point.
1412 /// Note that the capacity of `self` does not change.
1416 /// Panics if `at` is not on a `UTF-8` code point boundary, or if it is beyond the last
1417 /// code point of the string.
1423 /// let mut hello = String::from("Hello, World!");
1424 /// let world = hello.split_off(7);
1425 /// assert_eq!(hello, "Hello, ");
1426 /// assert_eq!(world, "World!");
1430 #[stable(feature = "string_split_off", since = "1.16.0")]
1431 pub fn split_off(&mut self, at: usize) -> String {
1432 assert!(self.is_char_boundary(at));
1433 let other = self.vec.split_off(at);
1434 unsafe { String::from_utf8_unchecked(other) }
1437 /// Truncates this `String`, removing all contents.
1439 /// While this means the `String` will have a length of zero, it does not
1440 /// touch its capacity.
1447 /// let mut s = String::from("foo");
1451 /// assert!(s.is_empty());
1452 /// assert_eq!(0, s.len());
1453 /// assert_eq!(3, s.capacity());
1456 #[stable(feature = "rust1", since = "1.0.0")]
1457 pub fn clear(&mut self) {
1461 /// Creates a draining iterator that removes the specified range in the `String`
1462 /// and yields the removed `chars`.
1464 /// Note: The element range is removed even if the iterator is not
1465 /// consumed until the end.
1469 /// Panics if the starting point or end point do not lie on a [`char`]
1470 /// boundary, or if they're out of bounds.
1472 /// [`char`]: ../../std/primitive.char.html
1479 /// let mut s = String::from("α is alpha, β is beta");
1480 /// let beta_offset = s.find('β').unwrap_or(s.len());
1482 /// // Remove the range up until the β from the string
1483 /// let t: String = s.drain(..beta_offset).collect();
1484 /// assert_eq!(t, "α is alpha, ");
1485 /// assert_eq!(s, "β is beta");
1487 /// // A full range clears the string
1489 /// assert_eq!(s, "");
1491 #[stable(feature = "drain", since = "1.6.0")]
1492 pub fn drain<R>(&mut self, range: R) -> Drain<'_>
1493 where R: RangeBounds<usize>
1497 // The String version of Drain does not have the memory safety issues
1498 // of the vector version. The data is just plain bytes.
1499 // Because the range removal happens in Drop, if the Drain iterator is leaked,
1500 // the removal will not happen.
1501 let len = self.len();
1502 let start = match range.start_bound() {
1504 Excluded(&n) => n + 1,
1507 let end = match range.end_bound() {
1508 Included(&n) => n + 1,
1513 // Take out two simultaneous borrows. The &mut String won't be accessed
1514 // until iteration is over, in Drop.
1515 let self_ptr = self as *mut _;
1516 // slicing does the appropriate bounds checks
1517 let chars_iter = self[start..end].chars();
1527 /// Removes the specified range in the string,
1528 /// and replaces it with the given string.
1529 /// The given string doesn't need to be the same length as the range.
1533 /// Panics if the starting point or end point do not lie on a [`char`]
1534 /// boundary, or if they're out of bounds.
1536 /// [`char`]: ../../std/primitive.char.html
1537 /// [`Vec::splice`]: ../../std/vec/struct.Vec.html#method.splice
1544 /// let mut s = String::from("α is alpha, β is beta");
1545 /// let beta_offset = s.find('β').unwrap_or(s.len());
1547 /// // Replace the range up until the β from the string
1548 /// s.replace_range(..beta_offset, "Α is capital alpha; ");
1549 /// assert_eq!(s, "Α is capital alpha; β is beta");
1551 #[stable(feature = "splice", since = "1.27.0")]
1552 pub fn replace_range<R>(&mut self, range: R, replace_with: &str)
1553 where R: RangeBounds<usize>
1557 // Replace_range does not have the memory safety issues of a vector Splice.
1558 // of the vector version. The data is just plain bytes.
1560 match range.start_bound() {
1561 Included(&n) => assert!(self.is_char_boundary(n)),
1562 Excluded(&n) => assert!(self.is_char_boundary(n + 1)),
1565 match range.end_bound() {
1566 Included(&n) => assert!(self.is_char_boundary(n + 1)),
1567 Excluded(&n) => assert!(self.is_char_boundary(n)),
1573 }.splice(range, replace_with.bytes());
1576 /// Converts this `String` into a [`Box`]`<`[`str`]`>`.
1578 /// This will drop any excess capacity.
1580 /// [`Box`]: ../../std/boxed/struct.Box.html
1581 /// [`str`]: ../../std/primitive.str.html
1588 /// let s = String::from("hello");
1590 /// let b = s.into_boxed_str();
1592 #[stable(feature = "box_str", since = "1.4.0")]
1594 pub fn into_boxed_str(self) -> Box<str> {
1595 let slice = self.vec.into_boxed_slice();
1596 unsafe { from_boxed_utf8_unchecked(slice) }
1600 impl FromUtf8Error {
1601 /// Returns a slice of [`u8`]s bytes that were attempted to convert to a `String`.
1608 /// // some invalid bytes, in a vector
1609 /// let bytes = vec![0, 159];
1611 /// let value = String::from_utf8(bytes);
1613 /// assert_eq!(&[0, 159], value.unwrap_err().as_bytes());
1615 #[stable(feature = "from_utf8_error_as_bytes", since = "1.26.0")]
1616 pub fn as_bytes(&self) -> &[u8] {
1620 /// Returns the bytes that were attempted to convert to a `String`.
1622 /// This method is carefully constructed to avoid allocation. It will
1623 /// consume the error, moving out the bytes, so that a copy of the bytes
1624 /// does not need to be made.
1631 /// // some invalid bytes, in a vector
1632 /// let bytes = vec![0, 159];
1634 /// let value = String::from_utf8(bytes);
1636 /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
1638 #[stable(feature = "rust1", since = "1.0.0")]
1639 pub fn into_bytes(self) -> Vec<u8> {
1643 /// Fetch a `Utf8Error` to get more details about the conversion failure.
1645 /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
1646 /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
1647 /// an analogue to `FromUtf8Error`. See its documentation for more details
1650 /// [`Utf8Error`]: ../../std/str/struct.Utf8Error.html
1651 /// [`std::str`]: ../../std/str/index.html
1652 /// [`u8`]: ../../std/primitive.u8.html
1653 /// [`&str`]: ../../std/primitive.str.html
1660 /// // some invalid bytes, in a vector
1661 /// let bytes = vec![0, 159];
1663 /// let error = String::from_utf8(bytes).unwrap_err().utf8_error();
1665 /// // the first byte is invalid here
1666 /// assert_eq!(1, error.valid_up_to());
1668 #[stable(feature = "rust1", since = "1.0.0")]
1669 pub fn utf8_error(&self) -> Utf8Error {
1674 #[stable(feature = "rust1", since = "1.0.0")]
1675 impl fmt::Display for FromUtf8Error {
1676 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1677 fmt::Display::fmt(&self.error, f)
1681 #[stable(feature = "rust1", since = "1.0.0")]
1682 impl fmt::Display for FromUtf16Error {
1683 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1684 fmt::Display::fmt("invalid utf-16: lone surrogate found", f)
1688 #[stable(feature = "rust1", since = "1.0.0")]
1689 impl Clone for String {
1690 fn clone(&self) -> Self {
1691 String { vec: self.vec.clone() }
1694 fn clone_from(&mut self, source: &Self) {
1695 self.vec.clone_from(&source.vec);
1699 #[stable(feature = "rust1", since = "1.0.0")]
1700 impl FromIterator<char> for String {
1701 fn from_iter<I: IntoIterator<Item = char>>(iter: I) -> String {
1702 let mut buf = String::new();
1708 #[stable(feature = "string_from_iter_by_ref", since = "1.17.0")]
1709 impl<'a> FromIterator<&'a char> for String {
1710 fn from_iter<I: IntoIterator<Item = &'a char>>(iter: I) -> String {
1711 let mut buf = String::new();
1717 #[stable(feature = "rust1", since = "1.0.0")]
1718 impl<'a> FromIterator<&'a str> for String {
1719 fn from_iter<I: IntoIterator<Item = &'a str>>(iter: I) -> String {
1720 let mut buf = String::new();
1726 #[stable(feature = "extend_string", since = "1.4.0")]
1727 impl FromIterator<String> for String {
1728 fn from_iter<I: IntoIterator<Item = String>>(iter: I) -> String {
1729 let mut iterator = iter.into_iter();
1731 // Because we're iterating over `String`s, we can avoid at least
1732 // one allocation by getting the first string from the iterator
1733 // and appending to it all the subsequent strings.
1734 match iterator.next() {
1735 None => String::new(),
1737 buf.extend(iterator);
1744 #[stable(feature = "herd_cows", since = "1.19.0")]
1745 impl<'a> FromIterator<Cow<'a, str>> for String {
1746 fn from_iter<I: IntoIterator<Item = Cow<'a, str>>>(iter: I) -> String {
1747 let mut iterator = iter.into_iter();
1749 // Because we're iterating over CoWs, we can (potentially) avoid at least
1750 // one allocation by getting the first item and appending to it all the
1751 // subsequent items.
1752 match iterator.next() {
1753 None => String::new(),
1755 let mut buf = cow.into_owned();
1756 buf.extend(iterator);
1763 #[stable(feature = "rust1", since = "1.0.0")]
1764 impl Extend<char> for String {
1765 fn extend<I: IntoIterator<Item = char>>(&mut self, iter: I) {
1766 let iterator = iter.into_iter();
1767 let (lower_bound, _) = iterator.size_hint();
1768 self.reserve(lower_bound);
1769 iterator.for_each(move |c| self.push(c));
1773 #[stable(feature = "extend_ref", since = "1.2.0")]
1774 impl<'a> Extend<&'a char> for String {
1775 fn extend<I: IntoIterator<Item = &'a char>>(&mut self, iter: I) {
1776 self.extend(iter.into_iter().cloned());
1780 #[stable(feature = "rust1", since = "1.0.0")]
1781 impl<'a> Extend<&'a str> for String {
1782 fn extend<I: IntoIterator<Item = &'a str>>(&mut self, iter: I) {
1783 iter.into_iter().for_each(move |s| self.push_str(s));
1787 #[stable(feature = "extend_string", since = "1.4.0")]
1788 impl Extend<String> for String {
1789 fn extend<I: IntoIterator<Item = String>>(&mut self, iter: I) {
1790 iter.into_iter().for_each(move |s| self.push_str(&s));
1794 #[stable(feature = "herd_cows", since = "1.19.0")]
1795 impl<'a> Extend<Cow<'a, str>> for String {
1796 fn extend<I: IntoIterator<Item = Cow<'a, str>>>(&mut self, iter: I) {
1797 iter.into_iter().for_each(move |s| self.push_str(&s));
1801 /// A convenience impl that delegates to the impl for `&str`
1802 #[unstable(feature = "pattern",
1803 reason = "API not fully fleshed out and ready to be stabilized",
1805 impl<'a, 'b> Pattern<'a> for &'b String {
1806 type Searcher = <&'b str as Pattern<'a>>::Searcher;
1808 fn into_searcher(self, haystack: &'a str) -> <&'b str as Pattern<'a>>::Searcher {
1809 self[..].into_searcher(haystack)
1813 fn is_contained_in(self, haystack: &'a str) -> bool {
1814 self[..].is_contained_in(haystack)
1818 fn is_prefix_of(self, haystack: &'a str) -> bool {
1819 self[..].is_prefix_of(haystack)
1823 #[stable(feature = "rust1", since = "1.0.0")]
1824 impl PartialEq for String {
1826 fn eq(&self, other: &String) -> bool {
1827 PartialEq::eq(&self[..], &other[..])
1830 fn ne(&self, other: &String) -> bool {
1831 PartialEq::ne(&self[..], &other[..])
1835 macro_rules! impl_eq {
1836 ($lhs:ty, $rhs: ty) => {
1837 #[stable(feature = "rust1", since = "1.0.0")]
1838 #[allow(unused_lifetimes)]
1839 impl<'a, 'b> PartialEq<$rhs> for $lhs {
1841 fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
1843 fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
1846 #[stable(feature = "rust1", since = "1.0.0")]
1847 #[allow(unused_lifetimes)]
1848 impl<'a, 'b> PartialEq<$lhs> for $rhs {
1850 fn eq(&self, other: &$lhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
1852 fn ne(&self, other: &$lhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
1858 impl_eq! { String, str }
1859 impl_eq! { String, &'a str }
1860 impl_eq! { Cow<'a, str>, str }
1861 impl_eq! { Cow<'a, str>, &'b str }
1862 impl_eq! { Cow<'a, str>, String }
1864 #[stable(feature = "rust1", since = "1.0.0")]
1865 impl Default for String {
1866 /// Creates an empty `String`.
1868 fn default() -> String {
1873 #[stable(feature = "rust1", since = "1.0.0")]
1874 impl fmt::Display for String {
1876 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1877 fmt::Display::fmt(&**self, f)
1881 #[stable(feature = "rust1", since = "1.0.0")]
1882 impl fmt::Debug for String {
1884 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1885 fmt::Debug::fmt(&**self, f)
1889 #[stable(feature = "rust1", since = "1.0.0")]
1890 impl hash::Hash for String {
1892 fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
1893 (**self).hash(hasher)
1897 /// Implements the `+` operator for concatenating two strings.
1899 /// This consumes the `String` on the left-hand side and re-uses its buffer (growing it if
1900 /// necessary). This is done to avoid allocating a new `String` and copying the entire contents on
1901 /// every operation, which would lead to `O(n^2)` running time when building an `n`-byte string by
1902 /// repeated concatenation.
1904 /// The string on the right-hand side is only borrowed; its contents are copied into the returned
1909 /// Concatenating two `String`s takes the first by value and borrows the second:
1912 /// let a = String::from("hello");
1913 /// let b = String::from(" world");
1915 /// // `a` is moved and can no longer be used here.
1918 /// If you want to keep using the first `String`, you can clone it and append to the clone instead:
1921 /// let a = String::from("hello");
1922 /// let b = String::from(" world");
1923 /// let c = a.clone() + &b;
1924 /// // `a` is still valid here.
1927 /// Concatenating `&str` slices can be done by converting the first to a `String`:
1930 /// let a = "hello";
1931 /// let b = " world";
1932 /// let c = a.to_string() + b;
1934 #[stable(feature = "rust1", since = "1.0.0")]
1935 impl Add<&str> for String {
1936 type Output = String;
1939 fn add(mut self, other: &str) -> String {
1940 self.push_str(other);
1945 /// Implements the `+=` operator for appending to a `String`.
1947 /// This has the same behavior as the [`push_str`][String::push_str] method.
1948 #[stable(feature = "stringaddassign", since = "1.12.0")]
1949 impl AddAssign<&str> for String {
1951 fn add_assign(&mut self, other: &str) {
1952 self.push_str(other);
1956 #[stable(feature = "rust1", since = "1.0.0")]
1957 impl ops::Index<ops::Range<usize>> for String {
1961 fn index(&self, index: ops::Range<usize>) -> &str {
1965 #[stable(feature = "rust1", since = "1.0.0")]
1966 impl ops::Index<ops::RangeTo<usize>> for String {
1970 fn index(&self, index: ops::RangeTo<usize>) -> &str {
1974 #[stable(feature = "rust1", since = "1.0.0")]
1975 impl ops::Index<ops::RangeFrom<usize>> for String {
1979 fn index(&self, index: ops::RangeFrom<usize>) -> &str {
1983 #[stable(feature = "rust1", since = "1.0.0")]
1984 impl ops::Index<ops::RangeFull> for String {
1988 fn index(&self, _index: ops::RangeFull) -> &str {
1989 unsafe { str::from_utf8_unchecked(&self.vec) }
1992 #[stable(feature = "inclusive_range", since = "1.26.0")]
1993 impl ops::Index<ops::RangeInclusive<usize>> for String {
1997 fn index(&self, index: ops::RangeInclusive<usize>) -> &str {
1998 Index::index(&**self, index)
2001 #[stable(feature = "inclusive_range", since = "1.26.0")]
2002 impl ops::Index<ops::RangeToInclusive<usize>> for String {
2006 fn index(&self, index: ops::RangeToInclusive<usize>) -> &str {
2007 Index::index(&**self, index)
2011 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2012 impl ops::IndexMut<ops::Range<usize>> for String {
2014 fn index_mut(&mut self, index: ops::Range<usize>) -> &mut str {
2015 &mut self[..][index]
2018 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2019 impl ops::IndexMut<ops::RangeTo<usize>> for String {
2021 fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut str {
2022 &mut self[..][index]
2025 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2026 impl ops::IndexMut<ops::RangeFrom<usize>> for String {
2028 fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut str {
2029 &mut self[..][index]
2032 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2033 impl ops::IndexMut<ops::RangeFull> for String {
2035 fn index_mut(&mut self, _index: ops::RangeFull) -> &mut str {
2036 unsafe { str::from_utf8_unchecked_mut(&mut *self.vec) }
2039 #[stable(feature = "inclusive_range", since = "1.26.0")]
2040 impl ops::IndexMut<ops::RangeInclusive<usize>> for String {
2042 fn index_mut(&mut self, index: ops::RangeInclusive<usize>) -> &mut str {
2043 IndexMut::index_mut(&mut **self, index)
2046 #[stable(feature = "inclusive_range", since = "1.26.0")]
2047 impl ops::IndexMut<ops::RangeToInclusive<usize>> for String {
2049 fn index_mut(&mut self, index: ops::RangeToInclusive<usize>) -> &mut str {
2050 IndexMut::index_mut(&mut **self, index)
2054 #[stable(feature = "rust1", since = "1.0.0")]
2055 impl ops::Deref for String {
2059 fn deref(&self) -> &str {
2060 unsafe { str::from_utf8_unchecked(&self.vec) }
2064 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2065 impl ops::DerefMut for String {
2067 fn deref_mut(&mut self) -> &mut str {
2068 unsafe { str::from_utf8_unchecked_mut(&mut *self.vec) }
2072 /// An error when parsing a `String`.
2074 /// This `enum` is slightly awkward: it will never actually exist. This error is
2075 /// part of the type signature of the implementation of [`FromStr`] on
2076 /// [`String`]. The return type of [`from_str`], requires that an error be
2077 /// defined, but, given that a [`String`] can always be made into a new
2078 /// [`String`] without error, this type will never actually be returned. As
2079 /// such, it is only here to satisfy said signature, and is useless otherwise.
2081 /// [`FromStr`]: ../../std/str/trait.FromStr.html
2082 /// [`String`]: struct.String.html
2083 /// [`from_str`]: ../../std/str/trait.FromStr.html#tymethod.from_str
2084 #[stable(feature = "str_parse_error", since = "1.5.0")]
2085 pub type ParseError = core::convert::Infallible;
2087 #[stable(feature = "rust1", since = "1.0.0")]
2088 impl FromStr for String {
2089 type Err = core::convert::Infallible;
2091 fn from_str(s: &str) -> Result<String, ParseError> {
2097 /// A trait for converting a value to a `String`.
2099 /// This trait is automatically implemented for any type which implements the
2100 /// [`Display`] trait. As such, `ToString` shouldn't be implemented directly:
2101 /// [`Display`] should be implemented instead, and you get the `ToString`
2102 /// implementation for free.
2104 /// [`Display`]: ../../std/fmt/trait.Display.html
2105 #[stable(feature = "rust1", since = "1.0.0")]
2106 pub trait ToString {
2107 /// Converts the given value to a `String`.
2115 /// let five = String::from("5");
2117 /// assert_eq!(five, i.to_string());
2119 #[rustc_conversion_suggestion]
2120 #[stable(feature = "rust1", since = "1.0.0")]
2121 fn to_string(&self) -> String;
2126 /// In this implementation, the `to_string` method panics
2127 /// if the `Display` implementation returns an error.
2128 /// This indicates an incorrect `Display` implementation
2129 /// since `fmt::Write for String` never returns an error itself.
2130 #[stable(feature = "rust1", since = "1.0.0")]
2131 impl<T: fmt::Display + ?Sized> ToString for T {
2133 default fn to_string(&self) -> String {
2135 let mut buf = String::new();
2136 buf.write_fmt(format_args!("{}", self))
2137 .expect("a Display implementation returned an error unexpectedly");
2138 buf.shrink_to_fit();
2143 #[stable(feature = "str_to_string_specialization", since = "1.9.0")]
2144 impl ToString for str {
2146 fn to_string(&self) -> String {
2151 #[stable(feature = "cow_str_to_string_specialization", since = "1.17.0")]
2152 impl ToString for Cow<'_, str> {
2154 fn to_string(&self) -> String {
2159 #[stable(feature = "string_to_string_specialization", since = "1.17.0")]
2160 impl ToString for String {
2162 fn to_string(&self) -> String {
2167 #[stable(feature = "rust1", since = "1.0.0")]
2168 impl AsRef<str> for String {
2170 fn as_ref(&self) -> &str {
2175 #[stable(feature = "rust1", since = "1.0.0")]
2176 impl AsRef<[u8]> for String {
2178 fn as_ref(&self) -> &[u8] {
2183 #[stable(feature = "rust1", since = "1.0.0")]
2184 impl From<&str> for String {
2186 fn from(s: &str) -> String {
2191 #[stable(feature = "from_ref_string", since = "1.35.0")]
2192 impl From<&String> for String {
2194 fn from(s: &String) -> String {
2199 // note: test pulls in libstd, which causes errors here
2201 #[stable(feature = "string_from_box", since = "1.18.0")]
2202 impl From<Box<str>> for String {
2203 /// Converts the given boxed `str` slice to a `String`.
2204 /// It is notable that the `str` slice is owned.
2211 /// let s1: String = String::from("hello world");
2212 /// let s2: Box<str> = s1.into_boxed_str();
2213 /// let s3: String = String::from(s2);
2215 /// assert_eq!("hello world", s3)
2217 fn from(s: Box<str>) -> String {
2222 #[stable(feature = "box_from_str", since = "1.20.0")]
2223 impl From<String> for Box<str> {
2224 /// Converts the given `String` to a boxed `str` slice that is owned.
2231 /// let s1: String = String::from("hello world");
2232 /// let s2: Box<str> = Box::from(s1);
2233 /// let s3: String = String::from(s2);
2235 /// assert_eq!("hello world", s3)
2237 fn from(s: String) -> Box<str> {
2242 #[stable(feature = "string_from_cow_str", since = "1.14.0")]
2243 impl<'a> From<Cow<'a, str>> for String {
2244 fn from(s: Cow<'a, str>) -> String {
2249 #[stable(feature = "rust1", since = "1.0.0")]
2250 impl<'a> From<&'a str> for Cow<'a, str> {
2252 fn from(s: &'a str) -> Cow<'a, str> {
2257 #[stable(feature = "rust1", since = "1.0.0")]
2258 impl<'a> From<String> for Cow<'a, str> {
2260 fn from(s: String) -> Cow<'a, str> {
2265 #[stable(feature = "cow_from_string_ref", since = "1.28.0")]
2266 impl<'a> From<&'a String> for Cow<'a, str> {
2268 fn from(s: &'a String) -> Cow<'a, str> {
2269 Cow::Borrowed(s.as_str())
2273 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2274 impl<'a> FromIterator<char> for Cow<'a, str> {
2275 fn from_iter<I: IntoIterator<Item = char>>(it: I) -> Cow<'a, str> {
2276 Cow::Owned(FromIterator::from_iter(it))
2280 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2281 impl<'a, 'b> FromIterator<&'b str> for Cow<'a, str> {
2282 fn from_iter<I: IntoIterator<Item = &'b str>>(it: I) -> Cow<'a, str> {
2283 Cow::Owned(FromIterator::from_iter(it))
2287 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2288 impl<'a> FromIterator<String> for Cow<'a, str> {
2289 fn from_iter<I: IntoIterator<Item = String>>(it: I) -> Cow<'a, str> {
2290 Cow::Owned(FromIterator::from_iter(it))
2294 #[stable(feature = "from_string_for_vec_u8", since = "1.14.0")]
2295 impl From<String> for Vec<u8> {
2296 /// Converts the given `String` to a vector `Vec` that holds values of type `u8`.
2303 /// let s1 = String::from("hello world");
2304 /// let v1 = Vec::from(s1);
2307 /// println!("{}", b);
2310 fn from(string: String) -> Vec<u8> {
2315 #[stable(feature = "rust1", since = "1.0.0")]
2316 impl fmt::Write for String {
2318 fn write_str(&mut self, s: &str) -> fmt::Result {
2324 fn write_char(&mut self, c: char) -> fmt::Result {
2330 /// A draining iterator for `String`.
2332 /// This struct is created by the [`drain`] method on [`String`]. See its
2333 /// documentation for more.
2335 /// [`drain`]: struct.String.html#method.drain
2336 /// [`String`]: struct.String.html
2337 #[stable(feature = "drain", since = "1.6.0")]
2338 pub struct Drain<'a> {
2339 /// Will be used as &'a mut String in the destructor
2340 string: *mut String,
2341 /// Start of part to remove
2343 /// End of part to remove
2345 /// Current remaining range to remove
2349 #[stable(feature = "collection_debug", since = "1.17.0")]
2350 impl fmt::Debug for Drain<'_> {
2351 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2352 f.pad("Drain { .. }")
2356 #[stable(feature = "drain", since = "1.6.0")]
2357 unsafe impl Sync for Drain<'_> {}
2358 #[stable(feature = "drain", since = "1.6.0")]
2359 unsafe impl Send for Drain<'_> {}
2361 #[stable(feature = "drain", since = "1.6.0")]
2362 impl Drop for Drain<'_> {
2363 fn drop(&mut self) {
2365 // Use Vec::drain. "Reaffirm" the bounds checks to avoid
2366 // panic code being inserted again.
2367 let self_vec = (*self.string).as_mut_vec();
2368 if self.start <= self.end && self.end <= self_vec.len() {
2369 self_vec.drain(self.start..self.end);
2375 #[stable(feature = "drain", since = "1.6.0")]
2376 impl Iterator for Drain<'_> {
2380 fn next(&mut self) -> Option<char> {
2384 fn size_hint(&self) -> (usize, Option<usize>) {
2385 self.iter.size_hint()
2389 fn last(mut self) -> Option<char> {
2394 #[stable(feature = "drain", since = "1.6.0")]
2395 impl DoubleEndedIterator for Drain<'_> {
2397 fn next_back(&mut self) -> Option<char> {
2398 self.iter.next_back()
2402 #[stable(feature = "fused", since = "1.26.0")]
2403 impl FusedIterator for Drain<'_> {}