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
9 //! There are multiple ways to create a new [`String`] from a string literal:
12 //! let s = "Hello".to_string();
14 //! let s = String::from("world");
15 //! let s: String = "also this".into();
18 //! You can create a new [`String`] from an existing one by concatenating with
22 //! let s = "Hello".to_string();
24 //! let message = s + " world!";
27 //! If you have a vector of valid UTF-8 bytes, you can make a [`String`] out of
28 //! it. You can do the reverse too.
31 //! let sparkle_heart = vec![240, 159, 146, 150];
33 //! // We know these bytes are valid, so we'll use `unwrap()`.
34 //! let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
36 //! assert_eq!("💖", sparkle_heart);
38 //! let bytes = sparkle_heart.into_bytes();
40 //! assert_eq!(bytes, [240, 159, 146, 150]);
43 #![stable(feature = "rust1", since = "1.0.0")]
45 use core::char::{decode_utf16, REPLACEMENT_CHARACTER};
48 use core::iter::{FromIterator, FusedIterator};
49 use core::ops::Bound::{Excluded, Included, Unbounded};
50 use core::ops::{self, Add, AddAssign, Index, IndexMut, RangeBounds};
52 use core::str::{lossy, pattern::Pattern};
54 use crate::borrow::{Cow, ToOwned};
55 use crate::boxed::Box;
56 use crate::collections::TryReserveError;
57 use crate::str::{self, from_boxed_utf8_unchecked, Chars, FromStr, Utf8Error};
60 /// A UTF-8 encoded, growable string.
62 /// The `String` type is the most common string type that has ownership over the
63 /// contents of the string. It has a close relationship with its borrowed
64 /// counterpart, the primitive [`str`].
68 /// You can create a `String` from [a literal string][str] with [`String::from`]:
70 /// [`String::from`]: From::from
73 /// let hello = String::from("Hello, world!");
76 /// You can append a [`char`] to a `String` with the [`push`] method, and
77 /// append a [`&str`] with the [`push_str`] method:
80 /// let mut hello = String::from("Hello, ");
83 /// hello.push_str("orld!");
86 /// [`push`]: String::push
87 /// [`push_str`]: String::push_str
89 /// If you have a vector of UTF-8 bytes, you can create a `String` from it with
90 /// the [`from_utf8`] method:
93 /// // some bytes, in a vector
94 /// let sparkle_heart = vec![240, 159, 146, 150];
96 /// // We know these bytes are valid, so we'll use `unwrap()`.
97 /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
99 /// assert_eq!("💖", sparkle_heart);
102 /// [`from_utf8`]: String::from_utf8
106 /// `String`s are always valid UTF-8. This has a few implications, the first of
107 /// which is that if you need a non-UTF-8 string, consider [`OsString`]. It is
108 /// similar, but without the UTF-8 constraint. The second implication is that
109 /// you cannot index into a `String`:
111 /// ```compile_fail,E0277
114 /// println!("The first letter of s is {}", s[0]); // ERROR!!!
117 /// [`OsString`]: ../../std/ffi/struct.OsString.html
119 /// Indexing is intended to be a constant-time operation, but UTF-8 encoding
120 /// does not allow us to do this. Furthermore, it's not clear what sort of
121 /// thing the index should return: a byte, a codepoint, or a grapheme cluster.
122 /// The [`bytes`] and [`chars`] methods return iterators over the first
123 /// two, respectively.
125 /// [`bytes`]: str::bytes
126 /// [`chars`]: str::chars
130 /// `String`s implement [`Deref`]`<Target=str>`, and so inherit all of [`str`]'s
131 /// methods. In addition, this means that you can pass a `String` to a
132 /// function which takes a [`&str`] by using an ampersand (`&`):
135 /// fn takes_str(s: &str) { }
137 /// let s = String::from("Hello");
142 /// This will create a [`&str`] from the `String` and pass it in. This
143 /// conversion is very inexpensive, and so generally, functions will accept
144 /// [`&str`]s as arguments unless they need a `String` for some specific
147 /// In certain cases Rust doesn't have enough information to make this
148 /// conversion, known as [`Deref`] coercion. In the following example a string
149 /// slice [`&'a str`][`&str`] implements the trait `TraitExample`, and the function
150 /// `example_func` takes anything that implements the trait. In this case Rust
151 /// would need to make two implicit conversions, which Rust doesn't have the
152 /// means to do. For that reason, the following example will not compile.
154 /// ```compile_fail,E0277
155 /// trait TraitExample {}
157 /// impl<'a> TraitExample for &'a str {}
159 /// fn example_func<A: TraitExample>(example_arg: A) {}
161 /// let example_string = String::from("example_string");
162 /// example_func(&example_string);
165 /// There are two options that would work instead. The first would be to
166 /// change the line `example_func(&example_string);` to
167 /// `example_func(example_string.as_str());`, using the method [`as_str()`]
168 /// to explicitly extract the string slice containing the string. The second
169 /// way changes `example_func(&example_string);` to
170 /// `example_func(&*example_string);`. In this case we are dereferencing a
171 /// `String` to a [`str`][`&str`], then referencing the [`str`][`&str`] back to
172 /// [`&str`]. The second way is more idiomatic, however both work to do the
173 /// conversion explicitly rather than relying on the implicit conversion.
177 /// A `String` is made up of three components: a pointer to some bytes, a
178 /// length, and a capacity. The pointer points to an internal buffer `String`
179 /// uses to store its data. The length is the number of bytes currently stored
180 /// in the buffer, and the capacity is the size of the buffer in bytes. As such,
181 /// the length will always be less than or equal to the capacity.
183 /// This buffer is always stored on the heap.
185 /// You can look at these with the [`as_ptr`], [`len`], and [`capacity`]
191 /// let story = String::from("Once upon a time...");
193 // FIXME Update this when vec_into_raw_parts is stabilized
194 /// // Prevent automatically dropping the String's data
195 /// let mut story = mem::ManuallyDrop::new(story);
197 /// let ptr = story.as_mut_ptr();
198 /// let len = story.len();
199 /// let capacity = story.capacity();
201 /// // story has nineteen bytes
202 /// assert_eq!(19, len);
204 /// // We can re-build a String out of ptr, len, and capacity. This is all
205 /// // unsafe because we are responsible for making sure the components are
207 /// let s = unsafe { String::from_raw_parts(ptr, len, capacity) } ;
209 /// assert_eq!(String::from("Once upon a time..."), s);
212 /// [`as_ptr`]: str::as_ptr
213 /// [`len`]: String::len
214 /// [`capacity`]: String::capacity
216 /// If a `String` has enough capacity, adding elements to it will not
217 /// re-allocate. For example, consider this program:
220 /// let mut s = String::new();
222 /// println!("{}", s.capacity());
225 /// s.push_str("hello");
226 /// println!("{}", s.capacity());
230 /// This will output the following:
241 /// At first, we have no memory allocated at all, but as we append to the
242 /// string, it increases its capacity appropriately. If we instead use the
243 /// [`with_capacity`] method to allocate the correct capacity initially:
246 /// let mut s = String::with_capacity(25);
248 /// println!("{}", s.capacity());
251 /// s.push_str("hello");
252 /// println!("{}", s.capacity());
256 /// [`with_capacity`]: String::with_capacity
258 /// We end up with a different output:
269 /// Here, there's no need to allocate more memory inside the loop.
272 /// [`Deref`]: core::ops::Deref
273 /// [`as_str()`]: String::as_str
274 #[derive(PartialOrd, Eq, Ord)]
275 #[cfg_attr(not(test), rustc_diagnostic_item = "string_type")]
276 #[stable(feature = "rust1", since = "1.0.0")]
281 /// A possible error value when converting a `String` from a UTF-8 byte vector.
283 /// This type is the error type for the [`from_utf8`] method on [`String`]. It
284 /// is designed in such a way to carefully avoid reallocations: the
285 /// [`into_bytes`] method will give back the byte vector that was used in the
286 /// conversion attempt.
288 /// [`from_utf8`]: String::from_utf8
289 /// [`into_bytes`]: FromUtf8Error::into_bytes
291 /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
292 /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
293 /// an analogue to `FromUtf8Error`, and you can get one from a `FromUtf8Error`
294 /// through the [`utf8_error`] method.
296 /// [`Utf8Error`]: core::str::Utf8Error
297 /// [`std::str`]: core::str
299 /// [`utf8_error`]: Self::utf8_error
306 /// // some invalid bytes, in a vector
307 /// let bytes = vec![0, 159];
309 /// let value = String::from_utf8(bytes);
311 /// assert!(value.is_err());
312 /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
314 #[stable(feature = "rust1", since = "1.0.0")]
315 #[derive(Debug, Clone, PartialEq, Eq)]
316 pub struct FromUtf8Error {
321 /// A possible error value when converting a `String` from a UTF-16 byte slice.
323 /// This type is the error type for the [`from_utf16`] method on [`String`].
325 /// [`from_utf16`]: String::from_utf16
331 /// // 𝄞mu<invalid>ic
332 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
333 /// 0xD800, 0x0069, 0x0063];
335 /// assert!(String::from_utf16(v).is_err());
337 #[stable(feature = "rust1", since = "1.0.0")]
339 pub struct FromUtf16Error(());
342 /// Creates a new empty `String`.
344 /// Given that the `String` is empty, this will not allocate any initial
345 /// buffer. While that means that this initial operation is very
346 /// inexpensive, it may cause excessive allocation later when you add
347 /// data. If you have an idea of how much data the `String` will hold,
348 /// consider the [`with_capacity`] method to prevent excessive
351 /// [`with_capacity`]: String::with_capacity
358 /// let s = String::new();
361 #[rustc_const_stable(feature = "const_string_new", since = "1.32.0")]
362 #[stable(feature = "rust1", since = "1.0.0")]
363 pub const fn new() -> String {
364 String { vec: Vec::new() }
367 /// Creates a new empty `String` with a particular capacity.
369 /// `String`s have an internal buffer to hold their data. The capacity is
370 /// the length of that buffer, and can be queried with the [`capacity`]
371 /// method. This method creates an empty `String`, but one with an initial
372 /// buffer that can hold `capacity` bytes. This is useful when you may be
373 /// appending a bunch of data to the `String`, reducing the number of
374 /// reallocations it needs to do.
376 /// [`capacity`]: String::capacity
378 /// If the given capacity is `0`, no allocation will occur, and this method
379 /// is identical to the [`new`] method.
381 /// [`new`]: String::new
388 /// let mut s = String::with_capacity(10);
390 /// // The String contains no chars, even though it has capacity for more
391 /// assert_eq!(s.len(), 0);
393 /// // These are all done without reallocating...
394 /// let cap = s.capacity();
399 /// assert_eq!(s.capacity(), cap);
401 /// // ...but this may make the string reallocate
405 #[stable(feature = "rust1", since = "1.0.0")]
406 pub fn with_capacity(capacity: usize) -> String {
407 String { vec: Vec::with_capacity(capacity) }
410 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
411 // required for this method definition, is not available. Since we don't
412 // require this method for testing purposes, I'll just stub it
413 // NB see the slice::hack module in slice.rs for more information
416 pub fn from_str(_: &str) -> String {
417 panic!("not available with cfg(test)");
420 /// Converts a vector of bytes to a `String`.
422 /// A string ([`String`]) is made of bytes ([`u8`]), and a vector of bytes
423 /// ([`Vec<u8>`]) is made of bytes, so this function converts between the
424 /// two. Not all byte slices are valid `String`s, however: `String`
425 /// requires that it is valid UTF-8. `from_utf8()` checks to ensure that
426 /// the bytes are valid UTF-8, and then does the conversion.
428 /// If you are sure that the byte slice is valid UTF-8, and you don't want
429 /// to incur the overhead of the validity check, there is an unsafe version
430 /// of this function, [`from_utf8_unchecked`], which has the same behavior
431 /// but skips the check.
433 /// This method will take care to not copy the vector, for efficiency's
436 /// If you need a [`&str`] instead of a `String`, consider
437 /// [`str::from_utf8`].
439 /// The inverse of this method is [`into_bytes`].
443 /// Returns [`Err`] if the slice is not UTF-8 with a description as to why the
444 /// provided bytes are not UTF-8. The vector you moved in is also included.
451 /// // some bytes, in a vector
452 /// let sparkle_heart = vec![240, 159, 146, 150];
454 /// // We know these bytes are valid, so we'll use `unwrap()`.
455 /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
457 /// assert_eq!("💖", sparkle_heart);
463 /// // some invalid bytes, in a vector
464 /// let sparkle_heart = vec![0, 159, 146, 150];
466 /// assert!(String::from_utf8(sparkle_heart).is_err());
469 /// See the docs for [`FromUtf8Error`] for more details on what you can do
472 /// [`from_utf8_unchecked`]: String::from_utf8_unchecked
473 /// [`Vec<u8>`]: crate::vec::Vec
475 /// [`into_bytes`]: String::into_bytes
477 #[stable(feature = "rust1", since = "1.0.0")]
478 pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error> {
479 match str::from_utf8(&vec) {
480 Ok(..) => Ok(String { vec }),
481 Err(e) => Err(FromUtf8Error { bytes: vec, error: e }),
485 /// Converts a slice of bytes to a string, including invalid characters.
487 /// Strings are made of bytes ([`u8`]), and a slice of bytes
488 /// ([`&[u8]`][byteslice]) is made of bytes, so this function converts
489 /// between the two. Not all byte slices are valid strings, however: strings
490 /// are required to be valid UTF-8. During this conversion,
491 /// `from_utf8_lossy()` will replace any invalid UTF-8 sequences with
492 /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD], which looks like this: �
494 /// [byteslice]: ../../std/primitive.slice.html
495 /// [U+FFFD]: core::char::REPLACEMENT_CHARACTER
497 /// If you are sure that the byte slice is valid UTF-8, and you don't want
498 /// to incur the overhead of the conversion, there is an unsafe version
499 /// of this function, [`from_utf8_unchecked`], which has the same behavior
500 /// but skips the checks.
502 /// [`from_utf8_unchecked`]: String::from_utf8_unchecked
504 /// This function returns a [`Cow<'a, str>`]. If our byte slice is invalid
505 /// UTF-8, then we need to insert the replacement characters, which will
506 /// change the size of the string, and hence, require a `String`. But if
507 /// it's already valid UTF-8, we don't need a new allocation. This return
508 /// type allows us to handle both cases.
510 /// [`Cow<'a, str>`]: crate::borrow::Cow
517 /// // some bytes, in a vector
518 /// let sparkle_heart = vec![240, 159, 146, 150];
520 /// let sparkle_heart = String::from_utf8_lossy(&sparkle_heart);
522 /// assert_eq!("💖", sparkle_heart);
528 /// // some invalid bytes
529 /// let input = b"Hello \xF0\x90\x80World";
530 /// let output = String::from_utf8_lossy(input);
532 /// assert_eq!("Hello �World", output);
534 #[stable(feature = "rust1", since = "1.0.0")]
535 pub fn from_utf8_lossy(v: &[u8]) -> Cow<'_, str> {
536 let mut iter = lossy::Utf8Lossy::from_bytes(v).chunks();
538 let (first_valid, first_broken) = if let Some(chunk) = iter.next() {
539 let lossy::Utf8LossyChunk { valid, broken } = chunk;
540 if valid.len() == v.len() {
541 debug_assert!(broken.is_empty());
542 return Cow::Borrowed(valid);
546 return Cow::Borrowed("");
549 const REPLACEMENT: &str = "\u{FFFD}";
551 let mut res = String::with_capacity(v.len());
552 res.push_str(first_valid);
553 if !first_broken.is_empty() {
554 res.push_str(REPLACEMENT);
557 for lossy::Utf8LossyChunk { valid, broken } in iter {
559 if !broken.is_empty() {
560 res.push_str(REPLACEMENT);
567 /// Decode a UTF-16 encoded vector `v` into a `String`, returning [`Err`]
568 /// if `v` contains any invalid data.
576 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
577 /// 0x0073, 0x0069, 0x0063];
578 /// assert_eq!(String::from("𝄞music"),
579 /// String::from_utf16(v).unwrap());
581 /// // 𝄞mu<invalid>ic
582 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
583 /// 0xD800, 0x0069, 0x0063];
584 /// assert!(String::from_utf16(v).is_err());
586 #[stable(feature = "rust1", since = "1.0.0")]
587 pub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error> {
588 // This isn't done via collect::<Result<_, _>>() for performance reasons.
589 // FIXME: the function can be simplified again when #48994 is closed.
590 let mut ret = String::with_capacity(v.len());
591 for c in decode_utf16(v.iter().cloned()) {
595 return Err(FromUtf16Error(()));
601 /// Decode a UTF-16 encoded slice `v` into a `String`, replacing
602 /// invalid data with [the replacement character (`U+FFFD`)][U+FFFD].
604 /// Unlike [`from_utf8_lossy`] which returns a [`Cow<'a, str>`],
605 /// `from_utf16_lossy` returns a `String` since the UTF-16 to UTF-8
606 /// conversion requires a memory allocation.
608 /// [`from_utf8_lossy`]: String::from_utf8_lossy
609 /// [`Cow<'a, str>`]: crate::borrow::Cow
610 /// [U+FFFD]: core::char::REPLACEMENT_CHARACTER
617 /// // 𝄞mus<invalid>ic<invalid>
618 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
619 /// 0x0073, 0xDD1E, 0x0069, 0x0063,
622 /// assert_eq!(String::from("𝄞mus\u{FFFD}ic\u{FFFD}"),
623 /// String::from_utf16_lossy(v));
626 #[stable(feature = "rust1", since = "1.0.0")]
627 pub fn from_utf16_lossy(v: &[u16]) -> String {
628 decode_utf16(v.iter().cloned()).map(|r| r.unwrap_or(REPLACEMENT_CHARACTER)).collect()
631 /// Decomposes a `String` into its raw components.
633 /// Returns the raw pointer to the underlying data, the length of
634 /// the string (in bytes), and the allocated capacity of the data
635 /// (in bytes). These are the same arguments in the same order as
636 /// the arguments to [`from_raw_parts`].
638 /// After calling this function, the caller is responsible for the
639 /// memory previously managed by the `String`. The only way to do
640 /// this is to convert the raw pointer, length, and capacity back
641 /// into a `String` with the [`from_raw_parts`] function, allowing
642 /// the destructor to perform the cleanup.
644 /// [`from_raw_parts`]: String::from_raw_parts
649 /// #![feature(vec_into_raw_parts)]
650 /// let s = String::from("hello");
652 /// let (ptr, len, cap) = s.into_raw_parts();
654 /// let rebuilt = unsafe { String::from_raw_parts(ptr, len, cap) };
655 /// assert_eq!(rebuilt, "hello");
657 #[unstable(feature = "vec_into_raw_parts", reason = "new API", issue = "65816")]
658 pub fn into_raw_parts(self) -> (*mut u8, usize, usize) {
659 self.vec.into_raw_parts()
662 /// Creates a new `String` from a length, capacity, and pointer.
666 /// This is highly unsafe, due to the number of invariants that aren't
669 /// * The memory at `ptr` needs to have been previously allocated by the
670 /// same allocator the standard library uses, with a required alignment of exactly 1.
671 /// * `length` needs to be less than or equal to `capacity`.
672 /// * `capacity` needs to be the correct value.
674 /// Violating these may cause problems like corrupting the allocator's
675 /// internal data structures.
677 /// The ownership of `ptr` is effectively transferred to the
678 /// `String` which may then deallocate, reallocate or change the
679 /// contents of memory pointed to by the pointer at will. Ensure
680 /// that nothing else uses the pointer after calling this
691 /// let s = String::from("hello");
693 // FIXME Update this when vec_into_raw_parts is stabilized
694 /// // Prevent automatically dropping the String's data
695 /// let mut s = mem::ManuallyDrop::new(s);
697 /// let ptr = s.as_mut_ptr();
698 /// let len = s.len();
699 /// let capacity = s.capacity();
701 /// let s = String::from_raw_parts(ptr, len, capacity);
703 /// assert_eq!(String::from("hello"), s);
707 #[stable(feature = "rust1", since = "1.0.0")]
708 pub unsafe fn from_raw_parts(buf: *mut u8, length: usize, capacity: usize) -> String {
709 unsafe { String { vec: Vec::from_raw_parts(buf, length, capacity) } }
712 /// Converts a vector of bytes to a `String` without checking that the
713 /// string contains valid UTF-8.
715 /// See the safe version, [`from_utf8`], for more details.
717 /// [`from_utf8`]: String::from_utf8
721 /// This function is unsafe because it does not check that the bytes passed
722 /// to it are valid UTF-8. If this constraint is violated, it may cause
723 /// memory unsafety issues with future users of the `String`, as the rest of
724 /// the standard library assumes that `String`s are valid UTF-8.
731 /// // some bytes, in a vector
732 /// let sparkle_heart = vec![240, 159, 146, 150];
734 /// let sparkle_heart = unsafe {
735 /// String::from_utf8_unchecked(sparkle_heart)
738 /// assert_eq!("💖", sparkle_heart);
741 #[stable(feature = "rust1", since = "1.0.0")]
742 pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String {
743 String { vec: bytes }
746 /// Converts a `String` into a byte vector.
748 /// This consumes the `String`, so we do not need to copy its contents.
755 /// let s = String::from("hello");
756 /// let bytes = s.into_bytes();
758 /// assert_eq!(&[104, 101, 108, 108, 111][..], &bytes[..]);
761 #[stable(feature = "rust1", since = "1.0.0")]
762 pub fn into_bytes(self) -> Vec<u8> {
766 /// Extracts a string slice containing the entire `String`.
773 /// let s = String::from("foo");
775 /// assert_eq!("foo", s.as_str());
778 #[stable(feature = "string_as_str", since = "1.7.0")]
779 pub fn as_str(&self) -> &str {
783 /// Converts a `String` into a mutable string slice.
790 /// let mut s = String::from("foobar");
791 /// let s_mut_str = s.as_mut_str();
793 /// s_mut_str.make_ascii_uppercase();
795 /// assert_eq!("FOOBAR", s_mut_str);
798 #[stable(feature = "string_as_str", since = "1.7.0")]
799 pub fn as_mut_str(&mut self) -> &mut str {
803 /// Appends a given string slice onto the end of this `String`.
810 /// let mut s = String::from("foo");
812 /// s.push_str("bar");
814 /// assert_eq!("foobar", s);
817 #[stable(feature = "rust1", since = "1.0.0")]
818 pub fn push_str(&mut self, string: &str) {
819 self.vec.extend_from_slice(string.as_bytes())
822 /// Returns this `String`'s capacity, in bytes.
829 /// let s = String::with_capacity(10);
831 /// assert!(s.capacity() >= 10);
834 #[stable(feature = "rust1", since = "1.0.0")]
835 pub fn capacity(&self) -> usize {
839 /// Ensures that this `String`'s capacity is at least `additional` bytes
840 /// larger than its length.
842 /// The capacity may be increased by more than `additional` bytes if it
843 /// chooses, to prevent frequent reallocations.
845 /// If you do not want this "at least" behavior, see the [`reserve_exact`]
850 /// Panics if the new capacity overflows [`usize`].
852 /// [`reserve_exact`]: String::reserve_exact
859 /// let mut s = String::new();
863 /// assert!(s.capacity() >= 10);
866 /// This may not actually increase the capacity:
869 /// let mut s = String::with_capacity(10);
873 /// // s now has a length of 2 and a capacity of 10
874 /// assert_eq!(2, s.len());
875 /// assert_eq!(10, s.capacity());
877 /// // Since we already have an extra 8 capacity, calling this...
880 /// // ... doesn't actually increase.
881 /// assert_eq!(10, s.capacity());
884 #[stable(feature = "rust1", since = "1.0.0")]
885 pub fn reserve(&mut self, additional: usize) {
886 self.vec.reserve(additional)
889 /// Ensures that this `String`'s capacity is `additional` bytes
890 /// larger than its length.
892 /// Consider using the [`reserve`] method unless you absolutely know
893 /// better than the allocator.
895 /// [`reserve`]: String::reserve
899 /// Panics if the new capacity overflows `usize`.
906 /// let mut s = String::new();
908 /// s.reserve_exact(10);
910 /// assert!(s.capacity() >= 10);
913 /// This may not actually increase the capacity:
916 /// let mut s = String::with_capacity(10);
920 /// // s now has a length of 2 and a capacity of 10
921 /// assert_eq!(2, s.len());
922 /// assert_eq!(10, s.capacity());
924 /// // Since we already have an extra 8 capacity, calling this...
925 /// s.reserve_exact(8);
927 /// // ... doesn't actually increase.
928 /// assert_eq!(10, s.capacity());
931 #[stable(feature = "rust1", since = "1.0.0")]
932 pub fn reserve_exact(&mut self, additional: usize) {
933 self.vec.reserve_exact(additional)
936 /// Tries to reserve capacity for at least `additional` more elements to be inserted
937 /// in the given `String`. The collection may reserve more space to avoid
938 /// frequent reallocations. After calling `reserve`, capacity will be
939 /// greater than or equal to `self.len() + additional`. Does nothing if
940 /// capacity is already sufficient.
944 /// If the capacity overflows, or the allocator reports a failure, then an error
950 /// #![feature(try_reserve)]
951 /// use std::collections::TryReserveError;
953 /// fn process_data(data: &str) -> Result<String, TryReserveError> {
954 /// let mut output = String::new();
956 /// // Pre-reserve the memory, exiting if we can't
957 /// output.try_reserve(data.len())?;
959 /// // Now we know this can't OOM in the middle of our complex work
960 /// output.push_str(data);
964 /// # process_data("rust").expect("why is the test harness OOMing on 4 bytes?");
966 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
967 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
968 self.vec.try_reserve(additional)
971 /// Tries to reserves the minimum capacity for exactly `additional` more elements to
972 /// be inserted in the given `String`. After calling `reserve_exact`,
973 /// capacity will be greater than or equal to `self.len() + additional`.
974 /// Does nothing if the capacity is already sufficient.
976 /// Note that the allocator may give the collection more space than it
977 /// requests. Therefore, capacity can not be relied upon to be precisely
978 /// minimal. Prefer `reserve` if future insertions are expected.
982 /// If the capacity overflows, or the allocator reports a failure, then an error
988 /// #![feature(try_reserve)]
989 /// use std::collections::TryReserveError;
991 /// fn process_data(data: &str) -> Result<String, TryReserveError> {
992 /// let mut output = String::new();
994 /// // Pre-reserve the memory, exiting if we can't
995 /// output.try_reserve(data.len())?;
997 /// // Now we know this can't OOM in the middle of our complex work
998 /// output.push_str(data);
1002 /// # process_data("rust").expect("why is the test harness OOMing on 4 bytes?");
1004 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
1005 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
1006 self.vec.try_reserve_exact(additional)
1009 /// Shrinks the capacity of this `String` to match its length.
1016 /// let mut s = String::from("foo");
1019 /// assert!(s.capacity() >= 100);
1021 /// s.shrink_to_fit();
1022 /// assert_eq!(3, s.capacity());
1025 #[stable(feature = "rust1", since = "1.0.0")]
1026 pub fn shrink_to_fit(&mut self) {
1027 self.vec.shrink_to_fit()
1030 /// Shrinks the capacity of this `String` with a lower bound.
1032 /// The capacity will remain at least as large as both the length
1033 /// and the supplied value.
1035 /// Panics if the current capacity is smaller than the supplied
1036 /// minimum capacity.
1041 /// #![feature(shrink_to)]
1042 /// let mut s = String::from("foo");
1045 /// assert!(s.capacity() >= 100);
1047 /// s.shrink_to(10);
1048 /// assert!(s.capacity() >= 10);
1050 /// assert!(s.capacity() >= 3);
1053 #[unstable(feature = "shrink_to", reason = "new API", issue = "56431")]
1054 pub fn shrink_to(&mut self, min_capacity: usize) {
1055 self.vec.shrink_to(min_capacity)
1058 /// Appends the given [`char`] to the end of this `String`.
1065 /// let mut s = String::from("abc");
1071 /// assert_eq!("abc123", s);
1074 #[stable(feature = "rust1", since = "1.0.0")]
1075 pub fn push(&mut self, ch: char) {
1076 match ch.len_utf8() {
1077 1 => self.vec.push(ch as u8),
1078 _ => self.vec.extend_from_slice(ch.encode_utf8(&mut [0; 4]).as_bytes()),
1082 /// Returns a byte slice of this `String`'s contents.
1084 /// The inverse of this method is [`from_utf8`].
1086 /// [`from_utf8`]: String::from_utf8
1093 /// let s = String::from("hello");
1095 /// assert_eq!(&[104, 101, 108, 108, 111], s.as_bytes());
1098 #[stable(feature = "rust1", since = "1.0.0")]
1099 pub fn as_bytes(&self) -> &[u8] {
1103 /// Shortens this `String` to the specified length.
1105 /// If `new_len` is greater than the string's current length, this has no
1108 /// Note that this method has no effect on the allocated capacity
1113 /// Panics if `new_len` does not lie on a [`char`] boundary.
1120 /// let mut s = String::from("hello");
1124 /// assert_eq!("he", s);
1127 #[stable(feature = "rust1", since = "1.0.0")]
1128 pub fn truncate(&mut self, new_len: usize) {
1129 if new_len <= self.len() {
1130 assert!(self.is_char_boundary(new_len));
1131 self.vec.truncate(new_len)
1135 /// Removes the last character from the string buffer and returns it.
1137 /// Returns [`None`] if this `String` is empty.
1144 /// let mut s = String::from("foo");
1146 /// assert_eq!(s.pop(), Some('o'));
1147 /// assert_eq!(s.pop(), Some('o'));
1148 /// assert_eq!(s.pop(), Some('f'));
1150 /// assert_eq!(s.pop(), None);
1153 #[stable(feature = "rust1", since = "1.0.0")]
1154 pub fn pop(&mut self) -> Option<char> {
1155 let ch = self.chars().rev().next()?;
1156 let newlen = self.len() - ch.len_utf8();
1158 self.vec.set_len(newlen);
1163 /// Removes a [`char`] from this `String` at a byte position and returns it.
1165 /// This is an `O(n)` operation, as it requires copying every element in the
1170 /// Panics if `idx` is larger than or equal to the `String`'s length,
1171 /// or if it does not lie on a [`char`] boundary.
1178 /// let mut s = String::from("foo");
1180 /// assert_eq!(s.remove(0), 'f');
1181 /// assert_eq!(s.remove(1), 'o');
1182 /// assert_eq!(s.remove(0), 'o');
1185 #[stable(feature = "rust1", since = "1.0.0")]
1186 pub fn remove(&mut self, idx: usize) -> char {
1187 let ch = match self[idx..].chars().next() {
1189 None => panic!("cannot remove a char from the end of a string"),
1192 let next = idx + ch.len_utf8();
1193 let len = self.len();
1195 ptr::copy(self.vec.as_ptr().add(next), self.vec.as_mut_ptr().add(idx), len - next);
1196 self.vec.set_len(len - (next - idx));
1201 /// Retains only the characters specified by the predicate.
1203 /// In other words, remove all characters `c` such that `f(c)` returns `false`.
1204 /// This method operates in place, visiting each character exactly once in the
1205 /// original order, and preserves the order of the retained characters.
1210 /// let mut s = String::from("f_o_ob_ar");
1212 /// s.retain(|c| c != '_');
1214 /// assert_eq!(s, "foobar");
1217 /// The exact order may be useful for tracking external state, like an index.
1220 /// let mut s = String::from("abcde");
1221 /// let keep = [false, true, true, false, true];
1223 /// s.retain(|_| (keep[i], i += 1).0);
1224 /// assert_eq!(s, "bce");
1227 #[stable(feature = "string_retain", since = "1.26.0")]
1228 pub fn retain<F>(&mut self, mut f: F)
1230 F: FnMut(char) -> bool,
1232 let len = self.len();
1233 let mut del_bytes = 0;
1237 let ch = unsafe { self.get_unchecked(idx..len).chars().next().unwrap() };
1238 let ch_len = ch.len_utf8();
1241 del_bytes += ch_len;
1242 } else if del_bytes > 0 {
1245 self.vec.as_ptr().add(idx),
1246 self.vec.as_mut_ptr().add(idx - del_bytes),
1252 // Point idx to the next char
1258 self.vec.set_len(len - del_bytes);
1263 /// Inserts a character into this `String` at a byte position.
1265 /// This is an `O(n)` operation as it requires copying every element in the
1270 /// Panics if `idx` is larger than the `String`'s length, or if it does not
1271 /// lie on a [`char`] boundary.
1278 /// let mut s = String::with_capacity(3);
1280 /// s.insert(0, 'f');
1281 /// s.insert(1, 'o');
1282 /// s.insert(2, 'o');
1284 /// assert_eq!("foo", s);
1287 #[stable(feature = "rust1", since = "1.0.0")]
1288 pub fn insert(&mut self, idx: usize, ch: char) {
1289 assert!(self.is_char_boundary(idx));
1290 let mut bits = [0; 4];
1291 let bits = ch.encode_utf8(&mut bits).as_bytes();
1294 self.insert_bytes(idx, bits);
1298 unsafe fn insert_bytes(&mut self, idx: usize, bytes: &[u8]) {
1299 let len = self.len();
1300 let amt = bytes.len();
1301 self.vec.reserve(amt);
1304 ptr::copy(self.vec.as_ptr().add(idx), self.vec.as_mut_ptr().add(idx + amt), len - idx);
1305 ptr::copy(bytes.as_ptr(), self.vec.as_mut_ptr().add(idx), amt);
1306 self.vec.set_len(len + amt);
1310 /// Inserts a string slice into this `String` at a byte position.
1312 /// This is an `O(n)` operation as it requires copying every element in the
1317 /// Panics if `idx` is larger than the `String`'s length, or if it does not
1318 /// lie on a [`char`] boundary.
1325 /// let mut s = String::from("bar");
1327 /// s.insert_str(0, "foo");
1329 /// assert_eq!("foobar", s);
1332 #[stable(feature = "insert_str", since = "1.16.0")]
1333 pub fn insert_str(&mut self, idx: usize, string: &str) {
1334 assert!(self.is_char_boundary(idx));
1337 self.insert_bytes(idx, string.as_bytes());
1341 /// Returns a mutable reference to the contents of this `String`.
1345 /// This function is unsafe because it does not check that the bytes passed
1346 /// to it are valid UTF-8. If this constraint is violated, it may cause
1347 /// memory unsafety issues with future users of the `String`, as the rest of
1348 /// the standard library assumes that `String`s are valid UTF-8.
1355 /// let mut s = String::from("hello");
1358 /// let vec = s.as_mut_vec();
1359 /// assert_eq!(&[104, 101, 108, 108, 111][..], &vec[..]);
1363 /// assert_eq!(s, "olleh");
1366 #[stable(feature = "rust1", since = "1.0.0")]
1367 pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1371 /// Returns the length of this `String`, in bytes, not [`char`]s or
1372 /// graphemes. In other words, it may not be what a human considers the
1373 /// length of the string.
1380 /// let a = String::from("foo");
1381 /// assert_eq!(a.len(), 3);
1383 /// let fancy_f = String::from("ƒoo");
1384 /// assert_eq!(fancy_f.len(), 4);
1385 /// assert_eq!(fancy_f.chars().count(), 3);
1388 #[stable(feature = "rust1", since = "1.0.0")]
1389 pub fn len(&self) -> usize {
1393 /// Returns `true` if this `String` has a length of zero, and `false` otherwise.
1400 /// let mut v = String::new();
1401 /// assert!(v.is_empty());
1404 /// assert!(!v.is_empty());
1407 #[stable(feature = "rust1", since = "1.0.0")]
1408 pub fn is_empty(&self) -> bool {
1412 /// Splits the string into two at the given index.
1414 /// Returns a newly allocated `String`. `self` contains bytes `[0, at)`, and
1415 /// the returned `String` contains bytes `[at, len)`. `at` must be on the
1416 /// boundary of a UTF-8 code point.
1418 /// Note that the capacity of `self` does not change.
1422 /// Panics if `at` is not on a `UTF-8` code point boundary, or if it is beyond the last
1423 /// code point of the string.
1429 /// let mut hello = String::from("Hello, World!");
1430 /// let world = hello.split_off(7);
1431 /// assert_eq!(hello, "Hello, ");
1432 /// assert_eq!(world, "World!");
1436 #[stable(feature = "string_split_off", since = "1.16.0")]
1437 #[must_use = "use `.truncate()` if you don't need the other half"]
1438 pub fn split_off(&mut self, at: usize) -> String {
1439 assert!(self.is_char_boundary(at));
1440 let other = self.vec.split_off(at);
1441 unsafe { String::from_utf8_unchecked(other) }
1444 /// Truncates this `String`, removing all contents.
1446 /// While this means the `String` will have a length of zero, it does not
1447 /// touch its capacity.
1454 /// let mut s = String::from("foo");
1458 /// assert!(s.is_empty());
1459 /// assert_eq!(0, s.len());
1460 /// assert_eq!(3, s.capacity());
1463 #[stable(feature = "rust1", since = "1.0.0")]
1464 pub fn clear(&mut self) {
1468 /// Creates a draining iterator that removes the specified range in the `String`
1469 /// and yields the removed `chars`.
1471 /// Note: The element range is removed even if the iterator is not
1472 /// consumed until the end.
1476 /// Panics if the starting point or end point do not lie on a [`char`]
1477 /// boundary, or if they're out of bounds.
1484 /// let mut s = String::from("α is alpha, β is beta");
1485 /// let beta_offset = s.find('β').unwrap_or(s.len());
1487 /// // Remove the range up until the β from the string
1488 /// let t: String = s.drain(..beta_offset).collect();
1489 /// assert_eq!(t, "α is alpha, ");
1490 /// assert_eq!(s, "β is beta");
1492 /// // A full range clears the string
1494 /// assert_eq!(s, "");
1496 #[stable(feature = "drain", since = "1.6.0")]
1497 pub fn drain<R>(&mut self, range: R) -> Drain<'_>
1499 R: RangeBounds<usize>,
1503 // The String version of Drain does not have the memory safety issues
1504 // of the vector version. The data is just plain bytes.
1505 // Because the range removal happens in Drop, if the Drain iterator is leaked,
1506 // the removal will not happen.
1507 let len = self.len();
1508 let start = match range.start_bound() {
1510 Excluded(&n) => n + 1,
1513 let end = match range.end_bound() {
1514 Included(&n) => n + 1,
1519 // Take out two simultaneous borrows. The &mut String won't be accessed
1520 // until iteration is over, in Drop.
1521 let self_ptr = self as *mut _;
1522 // slicing does the appropriate bounds checks
1523 let chars_iter = self[start..end].chars();
1525 Drain { start, end, iter: chars_iter, string: self_ptr }
1528 /// Removes the specified range in the string,
1529 /// and replaces it with the given string.
1530 /// The given string doesn't need to be the same length as the range.
1534 /// Panics if the starting point or end point do not lie on a [`char`]
1535 /// boundary, or if they're out of bounds.
1542 /// let mut s = String::from("α is alpha, β is beta");
1543 /// let beta_offset = s.find('β').unwrap_or(s.len());
1545 /// // Replace the range up until the β from the string
1546 /// s.replace_range(..beta_offset, "Α is capital alpha; ");
1547 /// assert_eq!(s, "Α is capital alpha; β is beta");
1549 #[stable(feature = "splice", since = "1.27.0")]
1550 pub fn replace_range<R>(&mut self, range: R, replace_with: &str)
1552 R: RangeBounds<usize>,
1556 // Replace_range does not have the memory safety issues of a vector Splice.
1557 // of the vector version. The data is just plain bytes.
1559 match range.start_bound() {
1560 Included(&n) => assert!(self.is_char_boundary(n)),
1561 Excluded(&n) => assert!(self.is_char_boundary(n + 1)),
1564 match range.end_bound() {
1565 Included(&n) => assert!(self.is_char_boundary(n + 1)),
1566 Excluded(&n) => assert!(self.is_char_boundary(n)),
1570 unsafe { self.as_mut_vec() }.splice(range, replace_with.bytes());
1573 /// Converts this `String` into a [`Box`]`<`[`str`]`>`.
1575 /// This will drop any excess capacity.
1582 /// let s = String::from("hello");
1584 /// let b = s.into_boxed_str();
1586 #[stable(feature = "box_str", since = "1.4.0")]
1588 pub fn into_boxed_str(self) -> Box<str> {
1589 let slice = self.vec.into_boxed_slice();
1590 unsafe { from_boxed_utf8_unchecked(slice) }
1594 impl FromUtf8Error {
1595 /// Returns a slice of [`u8`]s bytes that were attempted to convert to a `String`.
1602 /// // some invalid bytes, in a vector
1603 /// let bytes = vec![0, 159];
1605 /// let value = String::from_utf8(bytes);
1607 /// assert_eq!(&[0, 159], value.unwrap_err().as_bytes());
1609 #[stable(feature = "from_utf8_error_as_bytes", since = "1.26.0")]
1610 pub fn as_bytes(&self) -> &[u8] {
1614 /// Returns the bytes that were attempted to convert to a `String`.
1616 /// This method is carefully constructed to avoid allocation. It will
1617 /// consume the error, moving out the bytes, so that a copy of the bytes
1618 /// does not need to be made.
1625 /// // some invalid bytes, in a vector
1626 /// let bytes = vec![0, 159];
1628 /// let value = String::from_utf8(bytes);
1630 /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
1632 #[stable(feature = "rust1", since = "1.0.0")]
1633 pub fn into_bytes(self) -> Vec<u8> {
1637 /// Fetch a `Utf8Error` to get more details about the conversion failure.
1639 /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
1640 /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
1641 /// an analogue to `FromUtf8Error`. See its documentation for more details
1644 /// [`std::str`]: core::str
1652 /// // some invalid bytes, in a vector
1653 /// let bytes = vec![0, 159];
1655 /// let error = String::from_utf8(bytes).unwrap_err().utf8_error();
1657 /// // the first byte is invalid here
1658 /// assert_eq!(1, error.valid_up_to());
1660 #[stable(feature = "rust1", since = "1.0.0")]
1661 pub fn utf8_error(&self) -> Utf8Error {
1666 #[stable(feature = "rust1", since = "1.0.0")]
1667 impl fmt::Display for FromUtf8Error {
1668 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1669 fmt::Display::fmt(&self.error, f)
1673 #[stable(feature = "rust1", since = "1.0.0")]
1674 impl fmt::Display for FromUtf16Error {
1675 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1676 fmt::Display::fmt("invalid utf-16: lone surrogate found", f)
1680 #[stable(feature = "rust1", since = "1.0.0")]
1681 impl Clone for String {
1682 fn clone(&self) -> Self {
1683 String { vec: self.vec.clone() }
1686 fn clone_from(&mut self, source: &Self) {
1687 self.vec.clone_from(&source.vec);
1691 #[stable(feature = "rust1", since = "1.0.0")]
1692 impl FromIterator<char> for String {
1693 fn from_iter<I: IntoIterator<Item = char>>(iter: I) -> String {
1694 let mut buf = String::new();
1700 #[stable(feature = "string_from_iter_by_ref", since = "1.17.0")]
1701 impl<'a> FromIterator<&'a char> for String {
1702 fn from_iter<I: IntoIterator<Item = &'a char>>(iter: I) -> String {
1703 let mut buf = String::new();
1709 #[stable(feature = "rust1", since = "1.0.0")]
1710 impl<'a> FromIterator<&'a str> for String {
1711 fn from_iter<I: IntoIterator<Item = &'a str>>(iter: I) -> String {
1712 let mut buf = String::new();
1718 #[stable(feature = "extend_string", since = "1.4.0")]
1719 impl FromIterator<String> for String {
1720 fn from_iter<I: IntoIterator<Item = String>>(iter: I) -> String {
1721 let mut iterator = iter.into_iter();
1723 // Because we're iterating over `String`s, we can avoid at least
1724 // one allocation by getting the first string from the iterator
1725 // and appending to it all the subsequent strings.
1726 match iterator.next() {
1727 None => String::new(),
1729 buf.extend(iterator);
1736 #[stable(feature = "box_str2", since = "1.45.0")]
1737 impl FromIterator<Box<str>> for String {
1738 fn from_iter<I: IntoIterator<Item = Box<str>>>(iter: I) -> String {
1739 let mut buf = String::new();
1745 #[stable(feature = "herd_cows", since = "1.19.0")]
1746 impl<'a> FromIterator<Cow<'a, str>> for String {
1747 fn from_iter<I: IntoIterator<Item = Cow<'a, str>>>(iter: I) -> String {
1748 let mut iterator = iter.into_iter();
1750 // Because we're iterating over CoWs, we can (potentially) avoid at least
1751 // one allocation by getting the first item and appending to it all the
1752 // subsequent items.
1753 match iterator.next() {
1754 None => String::new(),
1756 let mut buf = cow.into_owned();
1757 buf.extend(iterator);
1764 #[stable(feature = "rust1", since = "1.0.0")]
1765 impl Extend<char> for String {
1766 fn extend<I: IntoIterator<Item = char>>(&mut self, iter: I) {
1767 let iterator = iter.into_iter();
1768 let (lower_bound, _) = iterator.size_hint();
1769 self.reserve(lower_bound);
1770 iterator.for_each(move |c| self.push(c));
1774 fn extend_one(&mut self, c: char) {
1779 fn extend_reserve(&mut self, additional: usize) {
1780 self.reserve(additional);
1784 #[stable(feature = "extend_ref", since = "1.2.0")]
1785 impl<'a> Extend<&'a char> for String {
1786 fn extend<I: IntoIterator<Item = &'a char>>(&mut self, iter: I) {
1787 self.extend(iter.into_iter().cloned());
1791 fn extend_one(&mut self, &c: &'a char) {
1796 fn extend_reserve(&mut self, additional: usize) {
1797 self.reserve(additional);
1801 #[stable(feature = "rust1", since = "1.0.0")]
1802 impl<'a> Extend<&'a str> for String {
1803 fn extend<I: IntoIterator<Item = &'a str>>(&mut self, iter: I) {
1804 iter.into_iter().for_each(move |s| self.push_str(s));
1808 fn extend_one(&mut self, s: &'a str) {
1813 #[stable(feature = "box_str2", since = "1.45.0")]
1814 impl Extend<Box<str>> for String {
1815 fn extend<I: IntoIterator<Item = Box<str>>>(&mut self, iter: I) {
1816 iter.into_iter().for_each(move |s| self.push_str(&s));
1820 #[stable(feature = "extend_string", since = "1.4.0")]
1821 impl Extend<String> for String {
1822 fn extend<I: IntoIterator<Item = String>>(&mut self, iter: I) {
1823 iter.into_iter().for_each(move |s| self.push_str(&s));
1827 fn extend_one(&mut self, s: String) {
1832 #[stable(feature = "herd_cows", since = "1.19.0")]
1833 impl<'a> Extend<Cow<'a, str>> for String {
1834 fn extend<I: IntoIterator<Item = Cow<'a, str>>>(&mut self, iter: I) {
1835 iter.into_iter().for_each(move |s| self.push_str(&s));
1839 fn extend_one(&mut self, s: Cow<'a, str>) {
1844 /// A convenience impl that delegates to the impl for `&str`.
1849 /// assert_eq!(String::from("Hello world").find("world"), Some(6));
1852 feature = "pattern",
1853 reason = "API not fully fleshed out and ready to be stabilized",
1856 impl<'a, 'b> Pattern<'a> for &'b String {
1857 type Searcher = <&'b str as Pattern<'a>>::Searcher;
1859 fn into_searcher(self, haystack: &'a str) -> <&'b str as Pattern<'a>>::Searcher {
1860 self[..].into_searcher(haystack)
1864 fn is_contained_in(self, haystack: &'a str) -> bool {
1865 self[..].is_contained_in(haystack)
1869 fn is_prefix_of(self, haystack: &'a str) -> bool {
1870 self[..].is_prefix_of(haystack)
1874 fn strip_prefix_of(self, haystack: &'a str) -> Option<&'a str> {
1875 self[..].strip_prefix_of(haystack)
1879 fn is_suffix_of(self, haystack: &'a str) -> bool {
1880 self[..].is_suffix_of(haystack)
1884 fn strip_suffix_of(self, haystack: &'a str) -> Option<&'a str> {
1885 self[..].strip_suffix_of(haystack)
1889 #[stable(feature = "rust1", since = "1.0.0")]
1890 impl PartialEq for String {
1892 fn eq(&self, other: &String) -> bool {
1893 PartialEq::eq(&self[..], &other[..])
1896 fn ne(&self, other: &String) -> bool {
1897 PartialEq::ne(&self[..], &other[..])
1901 macro_rules! impl_eq {
1902 ($lhs:ty, $rhs: ty) => {
1903 #[stable(feature = "rust1", since = "1.0.0")]
1904 #[allow(unused_lifetimes)]
1905 impl<'a, 'b> PartialEq<$rhs> for $lhs {
1907 fn eq(&self, other: &$rhs) -> bool {
1908 PartialEq::eq(&self[..], &other[..])
1911 fn ne(&self, other: &$rhs) -> bool {
1912 PartialEq::ne(&self[..], &other[..])
1916 #[stable(feature = "rust1", since = "1.0.0")]
1917 #[allow(unused_lifetimes)]
1918 impl<'a, 'b> PartialEq<$lhs> for $rhs {
1920 fn eq(&self, other: &$lhs) -> bool {
1921 PartialEq::eq(&self[..], &other[..])
1924 fn ne(&self, other: &$lhs) -> bool {
1925 PartialEq::ne(&self[..], &other[..])
1931 impl_eq! { String, str }
1932 impl_eq! { String, &'a str }
1933 impl_eq! { Cow<'a, str>, str }
1934 impl_eq! { Cow<'a, str>, &'b str }
1935 impl_eq! { Cow<'a, str>, String }
1937 #[stable(feature = "rust1", since = "1.0.0")]
1938 impl Default for String {
1939 /// Creates an empty `String`.
1941 fn default() -> String {
1946 #[stable(feature = "rust1", since = "1.0.0")]
1947 impl fmt::Display for String {
1949 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1950 fmt::Display::fmt(&**self, f)
1954 #[stable(feature = "rust1", since = "1.0.0")]
1955 impl fmt::Debug for String {
1957 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1958 fmt::Debug::fmt(&**self, f)
1962 #[stable(feature = "rust1", since = "1.0.0")]
1963 impl hash::Hash for String {
1965 fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
1966 (**self).hash(hasher)
1970 /// Implements the `+` operator for concatenating two strings.
1972 /// This consumes the `String` on the left-hand side and re-uses its buffer (growing it if
1973 /// necessary). This is done to avoid allocating a new `String` and copying the entire contents on
1974 /// every operation, which would lead to `O(n^2)` running time when building an `n`-byte string by
1975 /// repeated concatenation.
1977 /// The string on the right-hand side is only borrowed; its contents are copied into the returned
1982 /// Concatenating two `String`s takes the first by value and borrows the second:
1985 /// let a = String::from("hello");
1986 /// let b = String::from(" world");
1988 /// // `a` is moved and can no longer be used here.
1991 /// If you want to keep using the first `String`, you can clone it and append to the clone instead:
1994 /// let a = String::from("hello");
1995 /// let b = String::from(" world");
1996 /// let c = a.clone() + &b;
1997 /// // `a` is still valid here.
2000 /// Concatenating `&str` slices can be done by converting the first to a `String`:
2003 /// let a = "hello";
2004 /// let b = " world";
2005 /// let c = a.to_string() + b;
2007 #[stable(feature = "rust1", since = "1.0.0")]
2008 impl Add<&str> for String {
2009 type Output = String;
2012 fn add(mut self, other: &str) -> String {
2013 self.push_str(other);
2018 /// Implements the `+=` operator for appending to a `String`.
2020 /// This has the same behavior as the [`push_str`][String::push_str] method.
2021 #[stable(feature = "stringaddassign", since = "1.12.0")]
2022 impl AddAssign<&str> for String {
2024 fn add_assign(&mut self, other: &str) {
2025 self.push_str(other);
2029 #[stable(feature = "rust1", since = "1.0.0")]
2030 impl ops::Index<ops::Range<usize>> for String {
2034 fn index(&self, index: ops::Range<usize>) -> &str {
2038 #[stable(feature = "rust1", since = "1.0.0")]
2039 impl ops::Index<ops::RangeTo<usize>> for String {
2043 fn index(&self, index: ops::RangeTo<usize>) -> &str {
2047 #[stable(feature = "rust1", since = "1.0.0")]
2048 impl ops::Index<ops::RangeFrom<usize>> for String {
2052 fn index(&self, index: ops::RangeFrom<usize>) -> &str {
2056 #[stable(feature = "rust1", since = "1.0.0")]
2057 impl ops::Index<ops::RangeFull> for String {
2061 fn index(&self, _index: ops::RangeFull) -> &str {
2062 unsafe { str::from_utf8_unchecked(&self.vec) }
2065 #[stable(feature = "inclusive_range", since = "1.26.0")]
2066 impl ops::Index<ops::RangeInclusive<usize>> for String {
2070 fn index(&self, index: ops::RangeInclusive<usize>) -> &str {
2071 Index::index(&**self, index)
2074 #[stable(feature = "inclusive_range", since = "1.26.0")]
2075 impl ops::Index<ops::RangeToInclusive<usize>> for String {
2079 fn index(&self, index: ops::RangeToInclusive<usize>) -> &str {
2080 Index::index(&**self, index)
2084 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2085 impl ops::IndexMut<ops::Range<usize>> for String {
2087 fn index_mut(&mut self, index: ops::Range<usize>) -> &mut str {
2088 &mut self[..][index]
2091 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2092 impl ops::IndexMut<ops::RangeTo<usize>> for String {
2094 fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut str {
2095 &mut self[..][index]
2098 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2099 impl ops::IndexMut<ops::RangeFrom<usize>> for String {
2101 fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut str {
2102 &mut self[..][index]
2105 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2106 impl ops::IndexMut<ops::RangeFull> for String {
2108 fn index_mut(&mut self, _index: ops::RangeFull) -> &mut str {
2109 unsafe { str::from_utf8_unchecked_mut(&mut *self.vec) }
2112 #[stable(feature = "inclusive_range", since = "1.26.0")]
2113 impl ops::IndexMut<ops::RangeInclusive<usize>> for String {
2115 fn index_mut(&mut self, index: ops::RangeInclusive<usize>) -> &mut str {
2116 IndexMut::index_mut(&mut **self, index)
2119 #[stable(feature = "inclusive_range", since = "1.26.0")]
2120 impl ops::IndexMut<ops::RangeToInclusive<usize>> for String {
2122 fn index_mut(&mut self, index: ops::RangeToInclusive<usize>) -> &mut str {
2123 IndexMut::index_mut(&mut **self, index)
2127 #[stable(feature = "rust1", since = "1.0.0")]
2128 impl ops::Deref for String {
2132 fn deref(&self) -> &str {
2133 unsafe { str::from_utf8_unchecked(&self.vec) }
2137 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2138 impl ops::DerefMut for String {
2140 fn deref_mut(&mut self) -> &mut str {
2141 unsafe { str::from_utf8_unchecked_mut(&mut *self.vec) }
2145 /// A type alias for [`Infallible`].
2147 /// This alias exists for backwards compatibility, and may be eventually deprecated.
2149 /// [`Infallible`]: core::convert::Infallible
2150 #[stable(feature = "str_parse_error", since = "1.5.0")]
2151 pub type ParseError = core::convert::Infallible;
2153 #[stable(feature = "rust1", since = "1.0.0")]
2154 impl FromStr for String {
2155 type Err = core::convert::Infallible;
2157 fn from_str(s: &str) -> Result<String, Self::Err> {
2162 /// A trait for converting a value to a `String`.
2164 /// This trait is automatically implemented for any type which implements the
2165 /// [`Display`] trait. As such, `ToString` shouldn't be implemented directly:
2166 /// [`Display`] should be implemented instead, and you get the `ToString`
2167 /// implementation for free.
2169 /// [`Display`]: fmt::Display
2170 #[stable(feature = "rust1", since = "1.0.0")]
2171 pub trait ToString {
2172 /// Converts the given value to a `String`.
2180 /// let five = String::from("5");
2182 /// assert_eq!(five, i.to_string());
2184 #[rustc_conversion_suggestion]
2185 #[stable(feature = "rust1", since = "1.0.0")]
2186 fn to_string(&self) -> String;
2191 /// In this implementation, the `to_string` method panics
2192 /// if the `Display` implementation returns an error.
2193 /// This indicates an incorrect `Display` implementation
2194 /// since `fmt::Write for String` never returns an error itself.
2195 #[stable(feature = "rust1", since = "1.0.0")]
2196 impl<T: fmt::Display + ?Sized> ToString for T {
2198 default fn to_string(&self) -> String {
2200 let mut buf = String::new();
2201 buf.write_fmt(format_args!("{}", self))
2202 .expect("a Display implementation returned an error unexpectedly");
2203 buf.shrink_to_fit();
2208 #[stable(feature = "char_to_string_specialization", since = "1.46.0")]
2209 impl ToString for char {
2211 fn to_string(&self) -> String {
2212 String::from(self.encode_utf8(&mut [0; 4]))
2216 #[stable(feature = "str_to_string_specialization", since = "1.9.0")]
2217 impl ToString for str {
2219 fn to_string(&self) -> String {
2224 #[stable(feature = "cow_str_to_string_specialization", since = "1.17.0")]
2225 impl ToString for Cow<'_, str> {
2227 fn to_string(&self) -> String {
2232 #[stable(feature = "string_to_string_specialization", since = "1.17.0")]
2233 impl ToString for String {
2235 fn to_string(&self) -> String {
2240 #[stable(feature = "rust1", since = "1.0.0")]
2241 impl AsRef<str> for String {
2243 fn as_ref(&self) -> &str {
2248 #[stable(feature = "string_as_mut", since = "1.43.0")]
2249 impl AsMut<str> for String {
2251 fn as_mut(&mut self) -> &mut str {
2256 #[stable(feature = "rust1", since = "1.0.0")]
2257 impl AsRef<[u8]> for String {
2259 fn as_ref(&self) -> &[u8] {
2264 #[stable(feature = "rust1", since = "1.0.0")]
2265 impl From<&str> for String {
2267 fn from(s: &str) -> String {
2272 #[stable(feature = "from_mut_str_for_string", since = "1.44.0")]
2273 impl From<&mut str> for String {
2274 /// Converts a `&mut str` into a `String`.
2276 /// The result is allocated on the heap.
2278 fn from(s: &mut str) -> String {
2283 #[stable(feature = "from_ref_string", since = "1.35.0")]
2284 impl From<&String> for String {
2286 fn from(s: &String) -> String {
2291 // note: test pulls in libstd, which causes errors here
2293 #[stable(feature = "string_from_box", since = "1.18.0")]
2294 impl From<Box<str>> for String {
2295 /// Converts the given boxed `str` slice to a `String`.
2296 /// It is notable that the `str` slice is owned.
2303 /// let s1: String = String::from("hello world");
2304 /// let s2: Box<str> = s1.into_boxed_str();
2305 /// let s3: String = String::from(s2);
2307 /// assert_eq!("hello world", s3)
2309 fn from(s: Box<str>) -> String {
2314 #[stable(feature = "box_from_str", since = "1.20.0")]
2315 impl From<String> for Box<str> {
2316 /// Converts the given `String` to a boxed `str` slice that is owned.
2323 /// let s1: String = String::from("hello world");
2324 /// let s2: Box<str> = Box::from(s1);
2325 /// let s3: String = String::from(s2);
2327 /// assert_eq!("hello world", s3)
2329 fn from(s: String) -> Box<str> {
2334 #[stable(feature = "string_from_cow_str", since = "1.14.0")]
2335 impl<'a> From<Cow<'a, str>> for String {
2336 fn from(s: Cow<'a, str>) -> String {
2341 #[stable(feature = "rust1", since = "1.0.0")]
2342 impl<'a> From<&'a str> for Cow<'a, str> {
2344 fn from(s: &'a str) -> Cow<'a, str> {
2349 #[stable(feature = "rust1", since = "1.0.0")]
2350 impl<'a> From<String> for Cow<'a, str> {
2352 fn from(s: String) -> Cow<'a, str> {
2357 #[stable(feature = "cow_from_string_ref", since = "1.28.0")]
2358 impl<'a> From<&'a String> for Cow<'a, str> {
2360 fn from(s: &'a String) -> Cow<'a, str> {
2361 Cow::Borrowed(s.as_str())
2365 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2366 impl<'a> FromIterator<char> for Cow<'a, str> {
2367 fn from_iter<I: IntoIterator<Item = char>>(it: I) -> Cow<'a, str> {
2368 Cow::Owned(FromIterator::from_iter(it))
2372 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2373 impl<'a, 'b> FromIterator<&'b str> for Cow<'a, str> {
2374 fn from_iter<I: IntoIterator<Item = &'b str>>(it: I) -> Cow<'a, str> {
2375 Cow::Owned(FromIterator::from_iter(it))
2379 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2380 impl<'a> FromIterator<String> for Cow<'a, str> {
2381 fn from_iter<I: IntoIterator<Item = String>>(it: I) -> Cow<'a, str> {
2382 Cow::Owned(FromIterator::from_iter(it))
2386 #[stable(feature = "from_string_for_vec_u8", since = "1.14.0")]
2387 impl From<String> for Vec<u8> {
2388 /// Converts the given `String` to a vector `Vec` that holds values of type `u8`.
2395 /// let s1 = String::from("hello world");
2396 /// let v1 = Vec::from(s1);
2399 /// println!("{}", b);
2402 fn from(string: String) -> Vec<u8> {
2407 #[stable(feature = "rust1", since = "1.0.0")]
2408 impl fmt::Write for String {
2410 fn write_str(&mut self, s: &str) -> fmt::Result {
2416 fn write_char(&mut self, c: char) -> fmt::Result {
2422 /// A draining iterator for `String`.
2424 /// This struct is created by the [`drain`] method on [`String`]. See its
2425 /// documentation for more.
2427 /// [`drain`]: String::drain
2428 #[stable(feature = "drain", since = "1.6.0")]
2429 pub struct Drain<'a> {
2430 /// Will be used as &'a mut String in the destructor
2431 string: *mut String,
2432 /// Start of part to remove
2434 /// End of part to remove
2436 /// Current remaining range to remove
2440 #[stable(feature = "collection_debug", since = "1.17.0")]
2441 impl fmt::Debug for Drain<'_> {
2442 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2443 f.pad("Drain { .. }")
2447 #[stable(feature = "drain", since = "1.6.0")]
2448 unsafe impl Sync for Drain<'_> {}
2449 #[stable(feature = "drain", since = "1.6.0")]
2450 unsafe impl Send for Drain<'_> {}
2452 #[stable(feature = "drain", since = "1.6.0")]
2453 impl Drop for Drain<'_> {
2454 fn drop(&mut self) {
2456 // Use Vec::drain. "Reaffirm" the bounds checks to avoid
2457 // panic code being inserted again.
2458 let self_vec = (*self.string).as_mut_vec();
2459 if self.start <= self.end && self.end <= self_vec.len() {
2460 self_vec.drain(self.start..self.end);
2466 #[stable(feature = "drain", since = "1.6.0")]
2467 impl Iterator for Drain<'_> {
2471 fn next(&mut self) -> Option<char> {
2475 fn size_hint(&self) -> (usize, Option<usize>) {
2476 self.iter.size_hint()
2480 fn last(mut self) -> Option<char> {
2485 #[stable(feature = "drain", since = "1.6.0")]
2486 impl DoubleEndedIterator for Drain<'_> {
2488 fn next_back(&mut self) -> Option<char> {
2489 self.iter.next_back()
2493 #[stable(feature = "fused", since = "1.26.0")]
2494 impl FusedIterator for Drain<'_> {}
2496 #[stable(feature = "from_char_for_string", since = "1.46.0")]
2497 impl From<char> for String {
2499 fn from(c: char) -> Self {