1 //! A UTF-8 encoded, growable string.
3 //! This module contains the [`String`] type, a trait for converting
4 //! [`ToString`]s, and several error types that may result from working with
7 //! [`ToString`]: trait.ToString.html
11 //! There are multiple ways to create a new [`String`] from a string literal:
14 //! let s = "Hello".to_string();
16 //! let s = String::from("world");
17 //! let s: String = "also this".into();
20 //! You can create a new [`String`] from an existing one by concatenating with
23 //! [`String`]: struct.String.html
26 //! let s = "Hello".to_string();
28 //! let message = s + " world!";
31 //! If you have a vector of valid UTF-8 bytes, you can make a [`String`] out of
32 //! it. You can do the reverse too.
35 //! let sparkle_heart = vec![240, 159, 146, 150];
37 //! // We know these bytes are valid, so we'll use `unwrap()`.
38 //! let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
40 //! assert_eq!("💖", sparkle_heart);
42 //! let bytes = sparkle_heart.into_bytes();
44 //! assert_eq!(bytes, [240, 159, 146, 150]);
47 #![stable(feature = "rust1", since = "1.0.0")]
49 use core::char::{decode_utf16, REPLACEMENT_CHARACTER};
52 use core::iter::{FromIterator, FusedIterator};
53 use core::ops::Bound::{Excluded, Included, Unbounded};
54 use core::ops::{self, Add, AddAssign, Index, IndexMut, RangeBounds};
56 use core::str::{lossy, pattern::Pattern};
58 use crate::borrow::{Cow, ToOwned};
59 use crate::boxed::Box;
60 use crate::collections::TryReserveError;
61 use crate::str::{self, from_boxed_utf8_unchecked, Chars, FromStr, Utf8Error};
64 /// A UTF-8 encoded, growable string.
66 /// The `String` type is the most common string type that has ownership over the
67 /// contents of the string. It has a close relationship with its borrowed
68 /// counterpart, the primitive [`str`].
70 /// [`str`]: ../../std/primitive.str.html
74 /// You can create a `String` from a literal string with [`String::from`]:
77 /// let hello = String::from("Hello, world!");
80 /// You can append a [`char`] to a `String` with the [`push`] method, and
81 /// append a [`&str`] with the [`push_str`] method:
84 /// let mut hello = String::from("Hello, ");
87 /// hello.push_str("orld!");
90 /// [`String::from`]: #method.from
91 /// [`char`]: ../../std/primitive.char.html
92 /// [`push`]: #method.push
93 /// [`push_str`]: #method.push_str
95 /// If you have a vector of UTF-8 bytes, you can create a `String` from it with
96 /// the [`from_utf8`] method:
99 /// // some bytes, in a vector
100 /// let sparkle_heart = vec![240, 159, 146, 150];
102 /// // We know these bytes are valid, so we'll use `unwrap()`.
103 /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
105 /// assert_eq!("💖", sparkle_heart);
108 /// [`from_utf8`]: #method.from_utf8
112 /// `String`s are always valid UTF-8. This has a few implications, the first of
113 /// which is that if you need a non-UTF-8 string, consider [`OsString`]. It is
114 /// similar, but without the UTF-8 constraint. The second implication is that
115 /// you cannot index into a `String`:
117 /// ```compile_fail,E0277
120 /// println!("The first letter of s is {}", s[0]); // ERROR!!!
123 /// [`OsString`]: ../../std/ffi/struct.OsString.html
125 /// Indexing is intended to be a constant-time operation, but UTF-8 encoding
126 /// does not allow us to do this. Furthermore, it's not clear what sort of
127 /// thing the index should return: a byte, a codepoint, or a grapheme cluster.
128 /// The [`bytes`] and [`chars`] methods return iterators over the first
129 /// two, respectively.
131 /// [`bytes`]: #method.bytes
132 /// [`chars`]: #method.chars
136 /// `String`s implement [`Deref`]`<Target=str>`, and so inherit all of [`str`]'s
137 /// methods. In addition, this means that you can pass a `String` to a
138 /// function which takes a [`&str`] by using an ampersand (`&`):
141 /// fn takes_str(s: &str) { }
143 /// let s = String::from("Hello");
148 /// This will create a [`&str`] from the `String` and pass it in. This
149 /// conversion is very inexpensive, and so generally, functions will accept
150 /// [`&str`]s as arguments unless they need a `String` for some specific
153 /// In certain cases Rust doesn't have enough information to make this
154 /// conversion, known as [`Deref`] coercion. In the following example a string
155 /// slice [`&'a str`][`&str`] implements the trait `TraitExample`, and the function
156 /// `example_func` takes anything that implements the trait. In this case Rust
157 /// would need to make two implicit conversions, which Rust doesn't have the
158 /// means to do. For that reason, the following example will not compile.
160 /// ```compile_fail,E0277
161 /// trait TraitExample {}
163 /// impl<'a> TraitExample for &'a str {}
165 /// fn example_func<A: TraitExample>(example_arg: A) {}
167 /// let example_string = String::from("example_string");
168 /// example_func(&example_string);
171 /// There are two options that would work instead. The first would be to
172 /// change the line `example_func(&example_string);` to
173 /// `example_func(example_string.as_str());`, using the method [`as_str()`]
174 /// to explicitly extract the string slice containing the string. The second
175 /// way changes `example_func(&example_string);` to
176 /// `example_func(&*example_string);`. In this case we are dereferencing a
177 /// `String` to a [`str`][`&str`], then referencing the [`str`][`&str`] back to
178 /// [`&str`]. The second way is more idiomatic, however both work to do the
179 /// conversion explicitly rather than relying on the implicit conversion.
183 /// A `String` is made up of three components: a pointer to some bytes, a
184 /// length, and a capacity. The pointer points to an internal buffer `String`
185 /// uses to store its data. The length is the number of bytes currently stored
186 /// in the buffer, and the capacity is the size of the buffer in bytes. As such,
187 /// the length will always be less than or equal to the capacity.
189 /// This buffer is always stored on the heap.
191 /// You can look at these with the [`as_ptr`], [`len`], and [`capacity`]
197 /// let story = String::from("Once upon a time...");
199 // FIXME Update this when vec_into_raw_parts is stabilized
200 /// // Prevent automatically dropping the String's data
201 /// let mut story = mem::ManuallyDrop::new(story);
203 /// let ptr = story.as_mut_ptr();
204 /// let len = story.len();
205 /// let capacity = story.capacity();
207 /// // story has nineteen bytes
208 /// assert_eq!(19, len);
210 /// // We can re-build a String out of ptr, len, and capacity. This is all
211 /// // unsafe because we are responsible for making sure the components are
213 /// let s = unsafe { String::from_raw_parts(ptr, len, capacity) } ;
215 /// assert_eq!(String::from("Once upon a time..."), s);
218 /// [`as_ptr`]: #method.as_ptr
219 /// [`len`]: #method.len
220 /// [`capacity`]: #method.capacity
222 /// If a `String` has enough capacity, adding elements to it will not
223 /// re-allocate. For example, consider this program:
226 /// let mut s = String::new();
228 /// println!("{}", s.capacity());
231 /// s.push_str("hello");
232 /// println!("{}", s.capacity());
236 /// This will output the following:
247 /// At first, we have no memory allocated at all, but as we append to the
248 /// string, it increases its capacity appropriately. If we instead use the
249 /// [`with_capacity`] method to allocate the correct capacity initially:
252 /// let mut s = String::with_capacity(25);
254 /// println!("{}", s.capacity());
257 /// s.push_str("hello");
258 /// println!("{}", s.capacity());
262 /// [`with_capacity`]: #method.with_capacity
264 /// We end up with a different output:
275 /// Here, there's no need to allocate more memory inside the loop.
277 /// [`&str`]: ../../std/primitive.str.html
278 /// [`Deref`]: ../../std/ops/trait.Deref.html
279 /// [`as_str()`]: struct.String.html#method.as_str
280 #[derive(PartialOrd, Eq, Ord)]
281 #[cfg_attr(not(test), rustc_diagnostic_item = "string_type")]
282 #[stable(feature = "rust1", since = "1.0.0")]
287 /// A possible error value when converting a `String` from a UTF-8 byte vector.
289 /// This type is the error type for the [`from_utf8`] method on [`String`]. It
290 /// is designed in such a way to carefully avoid reallocations: the
291 /// [`into_bytes`] method will give back the byte vector that was used in the
292 /// conversion attempt.
294 /// [`from_utf8`]: struct.String.html#method.from_utf8
295 /// [`String`]: struct.String.html
296 /// [`into_bytes`]: struct.FromUtf8Error.html#method.into_bytes
298 /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
299 /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
300 /// an analogue to `FromUtf8Error`, and you can get one from a `FromUtf8Error`
301 /// through the [`utf8_error`] method.
303 /// [`Utf8Error`]: ../../std/str/struct.Utf8Error.html
304 /// [`std::str`]: ../../std/str/index.html
305 /// [`u8`]: ../../std/primitive.u8.html
306 /// [`&str`]: ../../std/primitive.str.html
307 /// [`utf8_error`]: #method.utf8_error
314 /// // some invalid bytes, in a vector
315 /// let bytes = vec![0, 159];
317 /// let value = String::from_utf8(bytes);
319 /// assert!(value.is_err());
320 /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
322 #[stable(feature = "rust1", since = "1.0.0")]
323 #[derive(Debug, Clone, PartialEq, Eq)]
324 pub struct FromUtf8Error {
329 /// A possible error value when converting a `String` from a UTF-16 byte slice.
331 /// This type is the error type for the [`from_utf16`] method on [`String`].
333 /// [`from_utf16`]: struct.String.html#method.from_utf16
334 /// [`String`]: struct.String.html
341 /// // 𝄞mu<invalid>ic
342 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
343 /// 0xD800, 0x0069, 0x0063];
345 /// assert!(String::from_utf16(v).is_err());
347 #[stable(feature = "rust1", since = "1.0.0")]
349 pub struct FromUtf16Error(());
352 /// Creates a new empty `String`.
354 /// Given that the `String` is empty, this will not allocate any initial
355 /// buffer. While that means that this initial operation is very
356 /// inexpensive, it may cause excessive allocation later when you add
357 /// data. If you have an idea of how much data the `String` will hold,
358 /// consider the [`with_capacity`] method to prevent excessive
361 /// [`with_capacity`]: #method.with_capacity
368 /// let s = String::new();
371 #[rustc_const_stable(feature = "const_string_new", since = "1.32.0")]
372 #[stable(feature = "rust1", since = "1.0.0")]
373 pub const fn new() -> String {
374 String { vec: Vec::new() }
377 /// Creates a new empty `String` with a particular capacity.
379 /// `String`s have an internal buffer to hold their data. The capacity is
380 /// the length of that buffer, and can be queried with the [`capacity`]
381 /// method. This method creates an empty `String`, but one with an initial
382 /// buffer that can hold `capacity` bytes. This is useful when you may be
383 /// appending a bunch of data to the `String`, reducing the number of
384 /// reallocations it needs to do.
386 /// [`capacity`]: #method.capacity
388 /// If the given capacity is `0`, no allocation will occur, and this method
389 /// is identical to the [`new`] method.
391 /// [`new`]: #method.new
398 /// let mut s = String::with_capacity(10);
400 /// // The String contains no chars, even though it has capacity for more
401 /// assert_eq!(s.len(), 0);
403 /// // These are all done without reallocating...
404 /// let cap = s.capacity();
409 /// assert_eq!(s.capacity(), cap);
411 /// // ...but this may make the string reallocate
415 #[stable(feature = "rust1", since = "1.0.0")]
416 pub fn with_capacity(capacity: usize) -> String {
417 String { vec: Vec::with_capacity(capacity) }
420 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
421 // required for this method definition, is not available. Since we don't
422 // require this method for testing purposes, I'll just stub it
423 // NB see the slice::hack module in slice.rs for more information
426 pub fn from_str(_: &str) -> String {
427 panic!("not available with cfg(test)");
430 /// Converts a vector of bytes to a `String`.
432 /// A string ([`String`]) is made of bytes ([`u8`]), and a vector of bytes
433 /// ([`Vec<u8>`]) is made of bytes, so this function converts between the
434 /// two. Not all byte slices are valid `String`s, however: `String`
435 /// requires that it is valid UTF-8. `from_utf8()` checks to ensure that
436 /// the bytes are valid UTF-8, and then does the conversion.
438 /// If you are sure that the byte slice is valid UTF-8, and you don't want
439 /// to incur the overhead of the validity check, there is an unsafe version
440 /// of this function, [`from_utf8_unchecked`], which has the same behavior
441 /// but skips the check.
443 /// This method will take care to not copy the vector, for efficiency's
446 /// If you need a [`&str`] instead of a `String`, consider
447 /// [`str::from_utf8`].
449 /// The inverse of this method is [`into_bytes`].
453 /// Returns [`Err`] if the slice is not UTF-8 with a description as to why the
454 /// provided bytes are not UTF-8. The vector you moved in is also included.
461 /// // some bytes, in a vector
462 /// let sparkle_heart = vec![240, 159, 146, 150];
464 /// // We know these bytes are valid, so we'll use `unwrap()`.
465 /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
467 /// assert_eq!("💖", sparkle_heart);
473 /// // some invalid bytes, in a vector
474 /// let sparkle_heart = vec![0, 159, 146, 150];
476 /// assert!(String::from_utf8(sparkle_heart).is_err());
479 /// See the docs for [`FromUtf8Error`] for more details on what you can do
482 /// [`from_utf8_unchecked`]: struct.String.html#method.from_utf8_unchecked
483 /// [`String`]: struct.String.html
484 /// [`u8`]: ../../std/primitive.u8.html
485 /// [`Vec<u8>`]: ../../std/vec/struct.Vec.html
486 /// [`&str`]: ../../std/primitive.str.html
487 /// [`str::from_utf8`]: ../../std/str/fn.from_utf8.html
488 /// [`into_bytes`]: struct.String.html#method.into_bytes
489 /// [`FromUtf8Error`]: struct.FromUtf8Error.html
490 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
492 #[stable(feature = "rust1", since = "1.0.0")]
493 pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error> {
494 match str::from_utf8(&vec) {
495 Ok(..) => Ok(String { vec }),
496 Err(e) => Err(FromUtf8Error { bytes: vec, error: e }),
500 /// Converts a slice of bytes to a string, including invalid characters.
502 /// Strings are made of bytes ([`u8`]), and a slice of bytes
503 /// ([`&[u8]`][byteslice]) is made of bytes, so this function converts
504 /// between the two. Not all byte slices are valid strings, however: strings
505 /// are required to be valid UTF-8. During this conversion,
506 /// `from_utf8_lossy()` will replace any invalid UTF-8 sequences with
507 /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD], which looks like this: �
509 /// [`u8`]: ../../std/primitive.u8.html
510 /// [byteslice]: ../../std/primitive.slice.html
511 /// [U+FFFD]: ../char/constant.REPLACEMENT_CHARACTER.html
513 /// If you are sure that the byte slice is valid UTF-8, and you don't want
514 /// to incur the overhead of the conversion, there is an unsafe version
515 /// of this function, [`from_utf8_unchecked`], which has the same behavior
516 /// but skips the checks.
518 /// [`from_utf8_unchecked`]: struct.String.html#method.from_utf8_unchecked
520 /// This function returns a [`Cow<'a, str>`]. If our byte slice is invalid
521 /// UTF-8, then we need to insert the replacement characters, which will
522 /// change the size of the string, and hence, require a `String`. But if
523 /// it's already valid UTF-8, we don't need a new allocation. This return
524 /// type allows us to handle both cases.
526 /// [`Cow<'a, str>`]: ../../std/borrow/enum.Cow.html
533 /// // some bytes, in a vector
534 /// let sparkle_heart = vec![240, 159, 146, 150];
536 /// let sparkle_heart = String::from_utf8_lossy(&sparkle_heart);
538 /// assert_eq!("💖", sparkle_heart);
544 /// // some invalid bytes
545 /// let input = b"Hello \xF0\x90\x80World";
546 /// let output = String::from_utf8_lossy(input);
548 /// assert_eq!("Hello �World", output);
550 #[stable(feature = "rust1", since = "1.0.0")]
551 pub fn from_utf8_lossy(v: &[u8]) -> Cow<'_, str> {
552 let mut iter = lossy::Utf8Lossy::from_bytes(v).chunks();
554 let (first_valid, first_broken) = if let Some(chunk) = iter.next() {
555 let lossy::Utf8LossyChunk { valid, broken } = chunk;
556 if valid.len() == v.len() {
557 debug_assert!(broken.is_empty());
558 return Cow::Borrowed(valid);
562 return Cow::Borrowed("");
565 const REPLACEMENT: &str = "\u{FFFD}";
567 let mut res = String::with_capacity(v.len());
568 res.push_str(first_valid);
569 if !first_broken.is_empty() {
570 res.push_str(REPLACEMENT);
573 for lossy::Utf8LossyChunk { valid, broken } in iter {
575 if !broken.is_empty() {
576 res.push_str(REPLACEMENT);
583 /// Decode a UTF-16 encoded vector `v` into a `String`, returning [`Err`]
584 /// if `v` contains any invalid data.
586 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
594 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
595 /// 0x0073, 0x0069, 0x0063];
596 /// assert_eq!(String::from("𝄞music"),
597 /// String::from_utf16(v).unwrap());
599 /// // 𝄞mu<invalid>ic
600 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
601 /// 0xD800, 0x0069, 0x0063];
602 /// assert!(String::from_utf16(v).is_err());
604 #[stable(feature = "rust1", since = "1.0.0")]
605 pub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error> {
606 // This isn't done via collect::<Result<_, _>>() for performance reasons.
607 // FIXME: the function can be simplified again when #48994 is closed.
608 let mut ret = String::with_capacity(v.len());
609 for c in decode_utf16(v.iter().cloned()) {
613 return Err(FromUtf16Error(()));
619 /// Decode a UTF-16 encoded slice `v` into a `String`, replacing
620 /// invalid data with [the replacement character (`U+FFFD`)][U+FFFD].
622 /// Unlike [`from_utf8_lossy`] which returns a [`Cow<'a, str>`],
623 /// `from_utf16_lossy` returns a `String` since the UTF-16 to UTF-8
624 /// conversion requires a memory allocation.
626 /// [`from_utf8_lossy`]: #method.from_utf8_lossy
627 /// [`Cow<'a, str>`]: ../borrow/enum.Cow.html
628 /// [U+FFFD]: ../char/constant.REPLACEMENT_CHARACTER.html
635 /// // 𝄞mus<invalid>ic<invalid>
636 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
637 /// 0x0073, 0xDD1E, 0x0069, 0x0063,
640 /// assert_eq!(String::from("𝄞mus\u{FFFD}ic\u{FFFD}"),
641 /// String::from_utf16_lossy(v));
644 #[stable(feature = "rust1", since = "1.0.0")]
645 pub fn from_utf16_lossy(v: &[u16]) -> String {
646 decode_utf16(v.iter().cloned()).map(|r| r.unwrap_or(REPLACEMENT_CHARACTER)).collect()
649 /// Decomposes a `String` into its raw components.
651 /// Returns the raw pointer to the underlying data, the length of
652 /// the string (in bytes), and the allocated capacity of the data
653 /// (in bytes). These are the same arguments in the same order as
654 /// the arguments to [`from_raw_parts`].
656 /// After calling this function, the caller is responsible for the
657 /// memory previously managed by the `String`. The only way to do
658 /// this is to convert the raw pointer, length, and capacity back
659 /// into a `String` with the [`from_raw_parts`] function, allowing
660 /// the destructor to perform the cleanup.
662 /// [`from_raw_parts`]: #method.from_raw_parts
667 /// #![feature(vec_into_raw_parts)]
668 /// let s = String::from("hello");
670 /// let (ptr, len, cap) = s.into_raw_parts();
672 /// let rebuilt = unsafe { String::from_raw_parts(ptr, len, cap) };
673 /// assert_eq!(rebuilt, "hello");
675 #[unstable(feature = "vec_into_raw_parts", reason = "new API", issue = "65816")]
676 pub fn into_raw_parts(self) -> (*mut u8, usize, usize) {
677 self.vec.into_raw_parts()
680 /// Creates a new `String` from a length, capacity, and pointer.
684 /// This is highly unsafe, due to the number of invariants that aren't
687 /// * The memory at `ptr` needs to have been previously allocated by the
688 /// same allocator the standard library uses, with a required alignment of exactly 1.
689 /// * `length` needs to be less than or equal to `capacity`.
690 /// * `capacity` needs to be the correct value.
692 /// Violating these may cause problems like corrupting the allocator's
693 /// internal data structures.
695 /// The ownership of `ptr` is effectively transferred to the
696 /// `String` which may then deallocate, reallocate or change the
697 /// contents of memory pointed to by the pointer at will. Ensure
698 /// that nothing else uses the pointer after calling this
709 /// let s = String::from("hello");
711 // FIXME Update this when vec_into_raw_parts is stabilized
712 /// // Prevent automatically dropping the String's data
713 /// let mut s = mem::ManuallyDrop::new(s);
715 /// let ptr = s.as_mut_ptr();
716 /// let len = s.len();
717 /// let capacity = s.capacity();
719 /// let s = String::from_raw_parts(ptr, len, capacity);
721 /// assert_eq!(String::from("hello"), s);
725 #[stable(feature = "rust1", since = "1.0.0")]
726 pub unsafe fn from_raw_parts(buf: *mut u8, length: usize, capacity: usize) -> String {
727 String { vec: Vec::from_raw_parts(buf, length, capacity) }
730 /// Converts a vector of bytes to a `String` without checking that the
731 /// string contains valid UTF-8.
733 /// See the safe version, [`from_utf8`], for more details.
735 /// [`from_utf8`]: struct.String.html#method.from_utf8
739 /// This function is unsafe because it does not check that the bytes passed
740 /// to it are valid UTF-8. If this constraint is violated, it may cause
741 /// memory unsafety issues with future users of the `String`, as the rest of
742 /// the standard library assumes that `String`s are valid UTF-8.
749 /// // some bytes, in a vector
750 /// let sparkle_heart = vec![240, 159, 146, 150];
752 /// let sparkle_heart = unsafe {
753 /// String::from_utf8_unchecked(sparkle_heart)
756 /// assert_eq!("💖", sparkle_heart);
759 #[stable(feature = "rust1", since = "1.0.0")]
760 pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String {
761 String { vec: bytes }
764 /// Converts a `String` into a byte vector.
766 /// This consumes the `String`, so we do not need to copy its contents.
773 /// let s = String::from("hello");
774 /// let bytes = s.into_bytes();
776 /// assert_eq!(&[104, 101, 108, 108, 111][..], &bytes[..]);
779 #[stable(feature = "rust1", since = "1.0.0")]
780 pub fn into_bytes(self) -> Vec<u8> {
784 /// Extracts a string slice containing the entire `String`.
791 /// let s = String::from("foo");
793 /// assert_eq!("foo", s.as_str());
796 #[stable(feature = "string_as_str", since = "1.7.0")]
797 pub fn as_str(&self) -> &str {
801 /// Converts a `String` into a mutable string slice.
808 /// let mut s = String::from("foobar");
809 /// let s_mut_str = s.as_mut_str();
811 /// s_mut_str.make_ascii_uppercase();
813 /// assert_eq!("FOOBAR", s_mut_str);
816 #[stable(feature = "string_as_str", since = "1.7.0")]
817 pub fn as_mut_str(&mut self) -> &mut str {
821 /// Appends a given string slice onto the end of this `String`.
828 /// let mut s = String::from("foo");
830 /// s.push_str("bar");
832 /// assert_eq!("foobar", s);
835 #[stable(feature = "rust1", since = "1.0.0")]
836 pub fn push_str(&mut self, string: &str) {
837 self.vec.extend_from_slice(string.as_bytes())
840 /// Returns this `String`'s capacity, in bytes.
847 /// let s = String::with_capacity(10);
849 /// assert!(s.capacity() >= 10);
852 #[stable(feature = "rust1", since = "1.0.0")]
853 pub fn capacity(&self) -> usize {
857 /// Ensures that this `String`'s capacity is at least `additional` bytes
858 /// larger than its length.
860 /// The capacity may be increased by more than `additional` bytes if it
861 /// chooses, to prevent frequent reallocations.
863 /// If you do not want this "at least" behavior, see the [`reserve_exact`]
868 /// Panics if the new capacity overflows [`usize`].
870 /// [`reserve_exact`]: struct.String.html#method.reserve_exact
871 /// [`usize`]: ../../std/primitive.usize.html
878 /// let mut s = String::new();
882 /// assert!(s.capacity() >= 10);
885 /// This may not actually increase the capacity:
888 /// let mut s = String::with_capacity(10);
892 /// // s now has a length of 2 and a capacity of 10
893 /// assert_eq!(2, s.len());
894 /// assert_eq!(10, s.capacity());
896 /// // Since we already have an extra 8 capacity, calling this...
899 /// // ... doesn't actually increase.
900 /// assert_eq!(10, s.capacity());
903 #[stable(feature = "rust1", since = "1.0.0")]
904 pub fn reserve(&mut self, additional: usize) {
905 self.vec.reserve(additional)
908 /// Ensures that this `String`'s capacity is `additional` bytes
909 /// larger than its length.
911 /// Consider using the [`reserve`] method unless you absolutely know
912 /// better than the allocator.
914 /// [`reserve`]: #method.reserve
918 /// Panics if the new capacity overflows `usize`.
925 /// let mut s = String::new();
927 /// s.reserve_exact(10);
929 /// assert!(s.capacity() >= 10);
932 /// This may not actually increase the capacity:
935 /// let mut s = String::with_capacity(10);
939 /// // s now has a length of 2 and a capacity of 10
940 /// assert_eq!(2, s.len());
941 /// assert_eq!(10, s.capacity());
943 /// // Since we already have an extra 8 capacity, calling this...
944 /// s.reserve_exact(8);
946 /// // ... doesn't actually increase.
947 /// assert_eq!(10, s.capacity());
950 #[stable(feature = "rust1", since = "1.0.0")]
951 pub fn reserve_exact(&mut self, additional: usize) {
952 self.vec.reserve_exact(additional)
955 /// Tries to reserve capacity for at least `additional` more elements to be inserted
956 /// in the given `String`. The collection may reserve more space to avoid
957 /// frequent reallocations. After calling `reserve`, capacity will be
958 /// greater than or equal to `self.len() + additional`. Does nothing if
959 /// capacity is already sufficient.
963 /// If the capacity overflows, or the allocator reports a failure, then an error
969 /// #![feature(try_reserve)]
970 /// use std::collections::TryReserveError;
972 /// fn process_data(data: &str) -> Result<String, TryReserveError> {
973 /// let mut output = String::new();
975 /// // Pre-reserve the memory, exiting if we can't
976 /// output.try_reserve(data.len())?;
978 /// // Now we know this can't OOM in the middle of our complex work
979 /// output.push_str(data);
983 /// # process_data("rust").expect("why is the test harness OOMing on 4 bytes?");
985 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
986 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
987 self.vec.try_reserve(additional)
990 /// Tries to reserves the minimum capacity for exactly `additional` more elements to
991 /// be inserted in the given `String`. After calling `reserve_exact`,
992 /// capacity will be greater than or equal to `self.len() + additional`.
993 /// Does nothing if the capacity is already sufficient.
995 /// Note that the allocator may give the collection more space than it
996 /// requests. Therefore, capacity can not be relied upon to be precisely
997 /// minimal. Prefer `reserve` if future insertions are expected.
1001 /// If the capacity overflows, or the allocator reports a failure, then an error
1007 /// #![feature(try_reserve)]
1008 /// use std::collections::TryReserveError;
1010 /// fn process_data(data: &str) -> Result<String, TryReserveError> {
1011 /// let mut output = String::new();
1013 /// // Pre-reserve the memory, exiting if we can't
1014 /// output.try_reserve(data.len())?;
1016 /// // Now we know this can't OOM in the middle of our complex work
1017 /// output.push_str(data);
1021 /// # process_data("rust").expect("why is the test harness OOMing on 4 bytes?");
1023 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
1024 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
1025 self.vec.try_reserve_exact(additional)
1028 /// Shrinks the capacity of this `String` to match its length.
1035 /// let mut s = String::from("foo");
1038 /// assert!(s.capacity() >= 100);
1040 /// s.shrink_to_fit();
1041 /// assert_eq!(3, s.capacity());
1044 #[stable(feature = "rust1", since = "1.0.0")]
1045 pub fn shrink_to_fit(&mut self) {
1046 self.vec.shrink_to_fit()
1049 /// Shrinks the capacity of this `String` with a lower bound.
1051 /// The capacity will remain at least as large as both the length
1052 /// and the supplied value.
1054 /// Panics if the current capacity is smaller than the supplied
1055 /// minimum capacity.
1060 /// #![feature(shrink_to)]
1061 /// let mut s = String::from("foo");
1064 /// assert!(s.capacity() >= 100);
1066 /// s.shrink_to(10);
1067 /// assert!(s.capacity() >= 10);
1069 /// assert!(s.capacity() >= 3);
1072 #[unstable(feature = "shrink_to", reason = "new API", issue = "56431")]
1073 pub fn shrink_to(&mut self, min_capacity: usize) {
1074 self.vec.shrink_to(min_capacity)
1077 /// Appends the given [`char`] to the end of this `String`.
1079 /// [`char`]: ../../std/primitive.char.html
1086 /// let mut s = String::from("abc");
1092 /// assert_eq!("abc123", s);
1095 #[stable(feature = "rust1", since = "1.0.0")]
1096 pub fn push(&mut self, ch: char) {
1097 match ch.len_utf8() {
1098 1 => self.vec.push(ch as u8),
1099 _ => self.vec.extend_from_slice(ch.encode_utf8(&mut [0; 4]).as_bytes()),
1103 /// Returns a byte slice of this `String`'s contents.
1105 /// The inverse of this method is [`from_utf8`].
1107 /// [`from_utf8`]: #method.from_utf8
1114 /// let s = String::from("hello");
1116 /// assert_eq!(&[104, 101, 108, 108, 111], s.as_bytes());
1119 #[stable(feature = "rust1", since = "1.0.0")]
1120 pub fn as_bytes(&self) -> &[u8] {
1124 /// Shortens this `String` to the specified length.
1126 /// If `new_len` is greater than the string's current length, this has no
1129 /// Note that this method has no effect on the allocated capacity
1134 /// Panics if `new_len` does not lie on a [`char`] boundary.
1136 /// [`char`]: ../../std/primitive.char.html
1143 /// let mut s = String::from("hello");
1147 /// assert_eq!("he", s);
1150 #[stable(feature = "rust1", since = "1.0.0")]
1151 pub fn truncate(&mut self, new_len: usize) {
1152 if new_len <= self.len() {
1153 assert!(self.is_char_boundary(new_len));
1154 self.vec.truncate(new_len)
1158 /// Removes the last character from the string buffer and returns it.
1160 /// Returns [`None`] if this `String` is empty.
1162 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1169 /// let mut s = String::from("foo");
1171 /// assert_eq!(s.pop(), Some('o'));
1172 /// assert_eq!(s.pop(), Some('o'));
1173 /// assert_eq!(s.pop(), Some('f'));
1175 /// assert_eq!(s.pop(), None);
1178 #[stable(feature = "rust1", since = "1.0.0")]
1179 pub fn pop(&mut self) -> Option<char> {
1180 let ch = self.chars().rev().next()?;
1181 let newlen = self.len() - ch.len_utf8();
1183 self.vec.set_len(newlen);
1188 /// Removes a [`char`] from this `String` at a byte position and returns it.
1190 /// This is an `O(n)` operation, as it requires copying every element in the
1195 /// Panics if `idx` is larger than or equal to the `String`'s length,
1196 /// or if it does not lie on a [`char`] boundary.
1198 /// [`char`]: ../../std/primitive.char.html
1205 /// let mut s = String::from("foo");
1207 /// assert_eq!(s.remove(0), 'f');
1208 /// assert_eq!(s.remove(1), 'o');
1209 /// assert_eq!(s.remove(0), 'o');
1212 #[stable(feature = "rust1", since = "1.0.0")]
1213 pub fn remove(&mut self, idx: usize) -> char {
1214 let ch = match self[idx..].chars().next() {
1216 None => panic!("cannot remove a char from the end of a string"),
1219 let next = idx + ch.len_utf8();
1220 let len = self.len();
1222 ptr::copy(self.vec.as_ptr().add(next), self.vec.as_mut_ptr().add(idx), len - next);
1223 self.vec.set_len(len - (next - idx));
1228 /// Retains only the characters specified by the predicate.
1230 /// In other words, remove all characters `c` such that `f(c)` returns `false`.
1231 /// This method operates in place, visiting each character exactly once in the
1232 /// original order, and preserves the order of the retained characters.
1237 /// let mut s = String::from("f_o_ob_ar");
1239 /// s.retain(|c| c != '_');
1241 /// assert_eq!(s, "foobar");
1244 /// The exact order may be useful for tracking external state, like an index.
1247 /// let mut s = String::from("abcde");
1248 /// let keep = [false, true, true, false, true];
1250 /// s.retain(|_| (keep[i], i += 1).0);
1251 /// assert_eq!(s, "bce");
1254 #[stable(feature = "string_retain", since = "1.26.0")]
1255 pub fn retain<F>(&mut self, mut f: F)
1257 F: FnMut(char) -> bool,
1259 let len = self.len();
1260 let mut del_bytes = 0;
1264 let ch = unsafe { self.get_unchecked(idx..len).chars().next().unwrap() };
1265 let ch_len = ch.len_utf8();
1268 del_bytes += ch_len;
1269 } else if del_bytes > 0 {
1272 self.vec.as_ptr().add(idx),
1273 self.vec.as_mut_ptr().add(idx - del_bytes),
1279 // Point idx to the next char
1285 self.vec.set_len(len - del_bytes);
1290 /// Inserts a character into this `String` at a byte position.
1292 /// This is an `O(n)` operation as it requires copying every element in the
1297 /// Panics if `idx` is larger than the `String`'s length, or if it does not
1298 /// lie on a [`char`] boundary.
1300 /// [`char`]: ../../std/primitive.char.html
1307 /// let mut s = String::with_capacity(3);
1309 /// s.insert(0, 'f');
1310 /// s.insert(1, 'o');
1311 /// s.insert(2, 'o');
1313 /// assert_eq!("foo", s);
1316 #[stable(feature = "rust1", since = "1.0.0")]
1317 pub fn insert(&mut self, idx: usize, ch: char) {
1318 assert!(self.is_char_boundary(idx));
1319 let mut bits = [0; 4];
1320 let bits = ch.encode_utf8(&mut bits).as_bytes();
1323 self.insert_bytes(idx, bits);
1327 unsafe fn insert_bytes(&mut self, idx: usize, bytes: &[u8]) {
1328 let len = self.len();
1329 let amt = bytes.len();
1330 self.vec.reserve(amt);
1332 ptr::copy(self.vec.as_ptr().add(idx), self.vec.as_mut_ptr().add(idx + amt), len - idx);
1333 ptr::copy(bytes.as_ptr(), self.vec.as_mut_ptr().add(idx), amt);
1334 self.vec.set_len(len + amt);
1337 /// Inserts a string slice into this `String` at a byte position.
1339 /// This is an `O(n)` operation as it requires copying every element in the
1344 /// Panics if `idx` is larger than the `String`'s length, or if it does not
1345 /// lie on a [`char`] boundary.
1347 /// [`char`]: ../../std/primitive.char.html
1354 /// let mut s = String::from("bar");
1356 /// s.insert_str(0, "foo");
1358 /// assert_eq!("foobar", s);
1361 #[stable(feature = "insert_str", since = "1.16.0")]
1362 pub fn insert_str(&mut self, idx: usize, string: &str) {
1363 assert!(self.is_char_boundary(idx));
1366 self.insert_bytes(idx, string.as_bytes());
1370 /// Returns a mutable reference to the contents of this `String`.
1374 /// This function is unsafe because it does not check that the bytes passed
1375 /// to it are valid UTF-8. If this constraint is violated, it may cause
1376 /// memory unsafety issues with future users of the `String`, as the rest of
1377 /// the standard library assumes that `String`s are valid UTF-8.
1384 /// let mut s = String::from("hello");
1387 /// let vec = s.as_mut_vec();
1388 /// assert_eq!(&[104, 101, 108, 108, 111][..], &vec[..]);
1392 /// assert_eq!(s, "olleh");
1395 #[stable(feature = "rust1", since = "1.0.0")]
1396 pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1400 /// Returns the length of this `String`, in bytes, not [`char`]s or
1401 /// graphemes. In other words, it may not be what a human considers the
1402 /// length of the string.
1409 /// let a = String::from("foo");
1410 /// assert_eq!(a.len(), 3);
1412 /// let fancy_f = String::from("ƒoo");
1413 /// assert_eq!(fancy_f.len(), 4);
1414 /// assert_eq!(fancy_f.chars().count(), 3);
1417 #[stable(feature = "rust1", since = "1.0.0")]
1418 pub fn len(&self) -> usize {
1422 /// Returns `true` if this `String` has a length of zero, and `false` otherwise.
1429 /// let mut v = String::new();
1430 /// assert!(v.is_empty());
1433 /// assert!(!v.is_empty());
1436 #[stable(feature = "rust1", since = "1.0.0")]
1437 pub fn is_empty(&self) -> bool {
1441 /// Splits the string into two at the given index.
1443 /// Returns a newly allocated `String`. `self` contains bytes `[0, at)`, and
1444 /// the returned `String` contains bytes `[at, len)`. `at` must be on the
1445 /// boundary of a UTF-8 code point.
1447 /// Note that the capacity of `self` does not change.
1451 /// Panics if `at` is not on a `UTF-8` code point boundary, or if it is beyond the last
1452 /// code point of the string.
1458 /// let mut hello = String::from("Hello, World!");
1459 /// let world = hello.split_off(7);
1460 /// assert_eq!(hello, "Hello, ");
1461 /// assert_eq!(world, "World!");
1465 #[stable(feature = "string_split_off", since = "1.16.0")]
1466 #[must_use = "use `.truncate()` if you don't need the other half"]
1467 pub fn split_off(&mut self, at: usize) -> String {
1468 assert!(self.is_char_boundary(at));
1469 let other = self.vec.split_off(at);
1470 unsafe { String::from_utf8_unchecked(other) }
1473 /// Truncates this `String`, removing all contents.
1475 /// While this means the `String` will have a length of zero, it does not
1476 /// touch its capacity.
1483 /// let mut s = String::from("foo");
1487 /// assert!(s.is_empty());
1488 /// assert_eq!(0, s.len());
1489 /// assert_eq!(3, s.capacity());
1492 #[stable(feature = "rust1", since = "1.0.0")]
1493 pub fn clear(&mut self) {
1497 /// Creates a draining iterator that removes the specified range in the `String`
1498 /// and yields the removed `chars`.
1500 /// Note: The element range is removed even if the iterator is not
1501 /// consumed until the end.
1505 /// Panics if the starting point or end point do not lie on a [`char`]
1506 /// boundary, or if they're out of bounds.
1508 /// [`char`]: ../../std/primitive.char.html
1515 /// let mut s = String::from("α is alpha, β is beta");
1516 /// let beta_offset = s.find('β').unwrap_or(s.len());
1518 /// // Remove the range up until the β from the string
1519 /// let t: String = s.drain(..beta_offset).collect();
1520 /// assert_eq!(t, "α is alpha, ");
1521 /// assert_eq!(s, "β is beta");
1523 /// // A full range clears the string
1525 /// assert_eq!(s, "");
1527 #[stable(feature = "drain", since = "1.6.0")]
1528 pub fn drain<R>(&mut self, range: R) -> Drain<'_>
1530 R: RangeBounds<usize>,
1534 // The String version of Drain does not have the memory safety issues
1535 // of the vector version. The data is just plain bytes.
1536 // Because the range removal happens in Drop, if the Drain iterator is leaked,
1537 // the removal will not happen.
1538 let len = self.len();
1539 let start = match range.start_bound() {
1541 Excluded(&n) => n + 1,
1544 let end = match range.end_bound() {
1545 Included(&n) => n + 1,
1550 // Take out two simultaneous borrows. The &mut String won't be accessed
1551 // until iteration is over, in Drop.
1552 let self_ptr = self as *mut _;
1553 // slicing does the appropriate bounds checks
1554 let chars_iter = self[start..end].chars();
1556 Drain { start, end, iter: chars_iter, string: self_ptr }
1559 /// Removes the specified range in the string,
1560 /// and replaces it with the given string.
1561 /// The given string doesn't need to be the same length as the range.
1565 /// Panics if the starting point or end point do not lie on a [`char`]
1566 /// boundary, or if they're out of bounds.
1568 /// [`char`]: ../../std/primitive.char.html
1569 /// [`Vec::splice`]: ../../std/vec/struct.Vec.html#method.splice
1576 /// let mut s = String::from("α is alpha, β is beta");
1577 /// let beta_offset = s.find('β').unwrap_or(s.len());
1579 /// // Replace the range up until the β from the string
1580 /// s.replace_range(..beta_offset, "Α is capital alpha; ");
1581 /// assert_eq!(s, "Α is capital alpha; β is beta");
1583 #[stable(feature = "splice", since = "1.27.0")]
1584 pub fn replace_range<R>(&mut self, range: R, replace_with: &str)
1586 R: RangeBounds<usize>,
1590 // Replace_range does not have the memory safety issues of a vector Splice.
1591 // of the vector version. The data is just plain bytes.
1593 match range.start_bound() {
1594 Included(&n) => assert!(self.is_char_boundary(n)),
1595 Excluded(&n) => assert!(self.is_char_boundary(n + 1)),
1598 match range.end_bound() {
1599 Included(&n) => assert!(self.is_char_boundary(n + 1)),
1600 Excluded(&n) => assert!(self.is_char_boundary(n)),
1604 unsafe { self.as_mut_vec() }.splice(range, replace_with.bytes());
1607 /// Converts this `String` into a [`Box`]`<`[`str`]`>`.
1609 /// This will drop any excess capacity.
1611 /// [`Box`]: ../../std/boxed/struct.Box.html
1612 /// [`str`]: ../../std/primitive.str.html
1619 /// let s = String::from("hello");
1621 /// let b = s.into_boxed_str();
1623 #[stable(feature = "box_str", since = "1.4.0")]
1625 pub fn into_boxed_str(self) -> Box<str> {
1626 let slice = self.vec.into_boxed_slice();
1627 unsafe { from_boxed_utf8_unchecked(slice) }
1631 impl FromUtf8Error {
1632 /// Returns a slice of [`u8`]s bytes that were attempted to convert to a `String`.
1639 /// // some invalid bytes, in a vector
1640 /// let bytes = vec![0, 159];
1642 /// let value = String::from_utf8(bytes);
1644 /// assert_eq!(&[0, 159], value.unwrap_err().as_bytes());
1646 #[stable(feature = "from_utf8_error_as_bytes", since = "1.26.0")]
1647 pub fn as_bytes(&self) -> &[u8] {
1651 /// Returns the bytes that were attempted to convert to a `String`.
1653 /// This method is carefully constructed to avoid allocation. It will
1654 /// consume the error, moving out the bytes, so that a copy of the bytes
1655 /// does not need to be made.
1662 /// // some invalid bytes, in a vector
1663 /// let bytes = vec![0, 159];
1665 /// let value = String::from_utf8(bytes);
1667 /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
1669 #[stable(feature = "rust1", since = "1.0.0")]
1670 pub fn into_bytes(self) -> Vec<u8> {
1674 /// Fetch a `Utf8Error` to get more details about the conversion failure.
1676 /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
1677 /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
1678 /// an analogue to `FromUtf8Error`. See its documentation for more details
1681 /// [`Utf8Error`]: ../../std/str/struct.Utf8Error.html
1682 /// [`std::str`]: ../../std/str/index.html
1683 /// [`u8`]: ../../std/primitive.u8.html
1684 /// [`&str`]: ../../std/primitive.str.html
1691 /// // some invalid bytes, in a vector
1692 /// let bytes = vec![0, 159];
1694 /// let error = String::from_utf8(bytes).unwrap_err().utf8_error();
1696 /// // the first byte is invalid here
1697 /// assert_eq!(1, error.valid_up_to());
1699 #[stable(feature = "rust1", since = "1.0.0")]
1700 pub fn utf8_error(&self) -> Utf8Error {
1705 #[stable(feature = "rust1", since = "1.0.0")]
1706 impl fmt::Display for FromUtf8Error {
1707 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1708 fmt::Display::fmt(&self.error, f)
1712 #[stable(feature = "rust1", since = "1.0.0")]
1713 impl fmt::Display for FromUtf16Error {
1714 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1715 fmt::Display::fmt("invalid utf-16: lone surrogate found", f)
1719 #[stable(feature = "rust1", since = "1.0.0")]
1720 impl Clone for String {
1721 fn clone(&self) -> Self {
1722 String { vec: self.vec.clone() }
1725 fn clone_from(&mut self, source: &Self) {
1726 self.vec.clone_from(&source.vec);
1730 #[stable(feature = "rust1", since = "1.0.0")]
1731 impl FromIterator<char> for String {
1732 fn from_iter<I: IntoIterator<Item = char>>(iter: I) -> String {
1733 let mut buf = String::new();
1739 #[stable(feature = "string_from_iter_by_ref", since = "1.17.0")]
1740 impl<'a> FromIterator<&'a char> for String {
1741 fn from_iter<I: IntoIterator<Item = &'a char>>(iter: I) -> String {
1742 let mut buf = String::new();
1748 #[stable(feature = "rust1", since = "1.0.0")]
1749 impl<'a> FromIterator<&'a str> for String {
1750 fn from_iter<I: IntoIterator<Item = &'a str>>(iter: I) -> String {
1751 let mut buf = String::new();
1757 #[stable(feature = "extend_string", since = "1.4.0")]
1758 impl FromIterator<String> for String {
1759 fn from_iter<I: IntoIterator<Item = String>>(iter: I) -> String {
1760 let mut iterator = iter.into_iter();
1762 // Because we're iterating over `String`s, we can avoid at least
1763 // one allocation by getting the first string from the iterator
1764 // and appending to it all the subsequent strings.
1765 match iterator.next() {
1766 None => String::new(),
1768 buf.extend(iterator);
1775 #[stable(feature = "herd_cows", since = "1.19.0")]
1776 impl<'a> FromIterator<Cow<'a, str>> for String {
1777 fn from_iter<I: IntoIterator<Item = Cow<'a, str>>>(iter: I) -> String {
1778 let mut iterator = iter.into_iter();
1780 // Because we're iterating over CoWs, we can (potentially) avoid at least
1781 // one allocation by getting the first item and appending to it all the
1782 // subsequent items.
1783 match iterator.next() {
1784 None => String::new(),
1786 let mut buf = cow.into_owned();
1787 buf.extend(iterator);
1794 #[stable(feature = "rust1", since = "1.0.0")]
1795 impl Extend<char> for String {
1796 fn extend<I: IntoIterator<Item = char>>(&mut self, iter: I) {
1797 let iterator = iter.into_iter();
1798 let (lower_bound, _) = iterator.size_hint();
1799 self.reserve(lower_bound);
1800 iterator.for_each(move |c| self.push(c));
1804 #[stable(feature = "extend_ref", since = "1.2.0")]
1805 impl<'a> Extend<&'a char> for String {
1806 fn extend<I: IntoIterator<Item = &'a char>>(&mut self, iter: I) {
1807 self.extend(iter.into_iter().cloned());
1811 #[stable(feature = "rust1", since = "1.0.0")]
1812 impl<'a> Extend<&'a str> for String {
1813 fn extend<I: IntoIterator<Item = &'a str>>(&mut self, iter: I) {
1814 iter.into_iter().for_each(move |s| self.push_str(s));
1818 #[stable(feature = "extend_string", since = "1.4.0")]
1819 impl Extend<String> for String {
1820 fn extend<I: IntoIterator<Item = String>>(&mut self, iter: I) {
1821 iter.into_iter().for_each(move |s| self.push_str(&s));
1825 #[stable(feature = "herd_cows", since = "1.19.0")]
1826 impl<'a> Extend<Cow<'a, str>> for String {
1827 fn extend<I: IntoIterator<Item = Cow<'a, str>>>(&mut self, iter: I) {
1828 iter.into_iter().for_each(move |s| self.push_str(&s));
1832 /// A convenience impl that delegates to the impl for `&str`.
1837 /// assert_eq!(String::from("Hello world").find("world"), Some(6));
1840 feature = "pattern",
1841 reason = "API not fully fleshed out and ready to be stabilized",
1844 impl<'a, 'b> Pattern<'a> for &'b String {
1845 type Searcher = <&'b str as Pattern<'a>>::Searcher;
1847 fn into_searcher(self, haystack: &'a str) -> <&'b str as Pattern<'a>>::Searcher {
1848 self[..].into_searcher(haystack)
1852 fn is_contained_in(self, haystack: &'a str) -> bool {
1853 self[..].is_contained_in(haystack)
1857 fn is_prefix_of(self, haystack: &'a str) -> bool {
1858 self[..].is_prefix_of(haystack)
1862 fn strip_prefix_of(self, haystack: &'a str) -> Option<&'a str> {
1863 self[..].strip_prefix_of(haystack)
1867 fn is_suffix_of(self, haystack: &'a str) -> bool {
1868 self[..].is_suffix_of(haystack)
1872 fn strip_suffix_of(self, haystack: &'a str) -> Option<&'a str> {
1873 self[..].strip_suffix_of(haystack)
1877 #[stable(feature = "rust1", since = "1.0.0")]
1878 impl PartialEq for String {
1880 fn eq(&self, other: &String) -> bool {
1881 PartialEq::eq(&self[..], &other[..])
1884 fn ne(&self, other: &String) -> bool {
1885 PartialEq::ne(&self[..], &other[..])
1889 macro_rules! impl_eq {
1890 ($lhs:ty, $rhs: ty) => {
1891 #[stable(feature = "rust1", since = "1.0.0")]
1892 #[allow(unused_lifetimes)]
1893 impl<'a, 'b> PartialEq<$rhs> for $lhs {
1895 fn eq(&self, other: &$rhs) -> bool {
1896 PartialEq::eq(&self[..], &other[..])
1899 fn ne(&self, other: &$rhs) -> bool {
1900 PartialEq::ne(&self[..], &other[..])
1904 #[stable(feature = "rust1", since = "1.0.0")]
1905 #[allow(unused_lifetimes)]
1906 impl<'a, 'b> PartialEq<$lhs> for $rhs {
1908 fn eq(&self, other: &$lhs) -> bool {
1909 PartialEq::eq(&self[..], &other[..])
1912 fn ne(&self, other: &$lhs) -> bool {
1913 PartialEq::ne(&self[..], &other[..])
1919 impl_eq! { String, str }
1920 impl_eq! { String, &'a str }
1921 impl_eq! { Cow<'a, str>, str }
1922 impl_eq! { Cow<'a, str>, &'b str }
1923 impl_eq! { Cow<'a, str>, String }
1925 #[stable(feature = "rust1", since = "1.0.0")]
1926 impl Default for String {
1927 /// Creates an empty `String`.
1929 fn default() -> String {
1934 #[stable(feature = "rust1", since = "1.0.0")]
1935 impl fmt::Display for String {
1937 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1938 fmt::Display::fmt(&**self, f)
1942 #[stable(feature = "rust1", since = "1.0.0")]
1943 impl fmt::Debug for String {
1945 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1946 fmt::Debug::fmt(&**self, f)
1950 #[stable(feature = "rust1", since = "1.0.0")]
1951 impl hash::Hash for String {
1953 fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
1954 (**self).hash(hasher)
1958 /// Implements the `+` operator for concatenating two strings.
1960 /// This consumes the `String` on the left-hand side and re-uses its buffer (growing it if
1961 /// necessary). This is done to avoid allocating a new `String` and copying the entire contents on
1962 /// every operation, which would lead to `O(n^2)` running time when building an `n`-byte string by
1963 /// repeated concatenation.
1965 /// The string on the right-hand side is only borrowed; its contents are copied into the returned
1970 /// Concatenating two `String`s takes the first by value and borrows the second:
1973 /// let a = String::from("hello");
1974 /// let b = String::from(" world");
1976 /// // `a` is moved and can no longer be used here.
1979 /// If you want to keep using the first `String`, you can clone it and append to the clone instead:
1982 /// let a = String::from("hello");
1983 /// let b = String::from(" world");
1984 /// let c = a.clone() + &b;
1985 /// // `a` is still valid here.
1988 /// Concatenating `&str` slices can be done by converting the first to a `String`:
1991 /// let a = "hello";
1992 /// let b = " world";
1993 /// let c = a.to_string() + b;
1995 #[stable(feature = "rust1", since = "1.0.0")]
1996 impl Add<&str> for String {
1997 type Output = String;
2000 fn add(mut self, other: &str) -> String {
2001 self.push_str(other);
2006 /// Implements the `+=` operator for appending to a `String`.
2008 /// This has the same behavior as the [`push_str`][String::push_str] method.
2009 #[stable(feature = "stringaddassign", since = "1.12.0")]
2010 impl AddAssign<&str> for String {
2012 fn add_assign(&mut self, other: &str) {
2013 self.push_str(other);
2017 #[stable(feature = "rust1", since = "1.0.0")]
2018 impl ops::Index<ops::Range<usize>> for String {
2022 fn index(&self, index: ops::Range<usize>) -> &str {
2026 #[stable(feature = "rust1", since = "1.0.0")]
2027 impl ops::Index<ops::RangeTo<usize>> for String {
2031 fn index(&self, index: ops::RangeTo<usize>) -> &str {
2035 #[stable(feature = "rust1", since = "1.0.0")]
2036 impl ops::Index<ops::RangeFrom<usize>> for String {
2040 fn index(&self, index: ops::RangeFrom<usize>) -> &str {
2044 #[stable(feature = "rust1", since = "1.0.0")]
2045 impl ops::Index<ops::RangeFull> for String {
2049 fn index(&self, _index: ops::RangeFull) -> &str {
2050 unsafe { str::from_utf8_unchecked(&self.vec) }
2053 #[stable(feature = "inclusive_range", since = "1.26.0")]
2054 impl ops::Index<ops::RangeInclusive<usize>> for String {
2058 fn index(&self, index: ops::RangeInclusive<usize>) -> &str {
2059 Index::index(&**self, index)
2062 #[stable(feature = "inclusive_range", since = "1.26.0")]
2063 impl ops::Index<ops::RangeToInclusive<usize>> for String {
2067 fn index(&self, index: ops::RangeToInclusive<usize>) -> &str {
2068 Index::index(&**self, index)
2072 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2073 impl ops::IndexMut<ops::Range<usize>> for String {
2075 fn index_mut(&mut self, index: ops::Range<usize>) -> &mut str {
2076 &mut self[..][index]
2079 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2080 impl ops::IndexMut<ops::RangeTo<usize>> for String {
2082 fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut str {
2083 &mut self[..][index]
2086 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2087 impl ops::IndexMut<ops::RangeFrom<usize>> for String {
2089 fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut str {
2090 &mut self[..][index]
2093 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2094 impl ops::IndexMut<ops::RangeFull> for String {
2096 fn index_mut(&mut self, _index: ops::RangeFull) -> &mut str {
2097 unsafe { str::from_utf8_unchecked_mut(&mut *self.vec) }
2100 #[stable(feature = "inclusive_range", since = "1.26.0")]
2101 impl ops::IndexMut<ops::RangeInclusive<usize>> for String {
2103 fn index_mut(&mut self, index: ops::RangeInclusive<usize>) -> &mut str {
2104 IndexMut::index_mut(&mut **self, index)
2107 #[stable(feature = "inclusive_range", since = "1.26.0")]
2108 impl ops::IndexMut<ops::RangeToInclusive<usize>> for String {
2110 fn index_mut(&mut self, index: ops::RangeToInclusive<usize>) -> &mut str {
2111 IndexMut::index_mut(&mut **self, index)
2115 #[stable(feature = "rust1", since = "1.0.0")]
2116 impl ops::Deref for String {
2120 fn deref(&self) -> &str {
2121 unsafe { str::from_utf8_unchecked(&self.vec) }
2125 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2126 impl ops::DerefMut for String {
2128 fn deref_mut(&mut self) -> &mut str {
2129 unsafe { str::from_utf8_unchecked_mut(&mut *self.vec) }
2133 /// A type alias for [`Infallible`].
2135 /// This alias exists for backwards compatibility, and may be eventually deprecated.
2137 /// [`Infallible`]: ../../core/convert/enum.Infallible.html
2138 #[stable(feature = "str_parse_error", since = "1.5.0")]
2139 pub type ParseError = core::convert::Infallible;
2141 #[stable(feature = "rust1", since = "1.0.0")]
2142 impl FromStr for String {
2143 type Err = core::convert::Infallible;
2145 fn from_str(s: &str) -> Result<String, Self::Err> {
2150 /// A trait for converting a value to a `String`.
2152 /// This trait is automatically implemented for any type which implements the
2153 /// [`Display`] trait. As such, `ToString` shouldn't be implemented directly:
2154 /// [`Display`] should be implemented instead, and you get the `ToString`
2155 /// implementation for free.
2157 /// [`Display`]: ../../std/fmt/trait.Display.html
2158 #[stable(feature = "rust1", since = "1.0.0")]
2159 pub trait ToString {
2160 /// Converts the given value to a `String`.
2168 /// let five = String::from("5");
2170 /// assert_eq!(five, i.to_string());
2172 #[rustc_conversion_suggestion]
2173 #[stable(feature = "rust1", since = "1.0.0")]
2174 fn to_string(&self) -> String;
2179 /// In this implementation, the `to_string` method panics
2180 /// if the `Display` implementation returns an error.
2181 /// This indicates an incorrect `Display` implementation
2182 /// since `fmt::Write for String` never returns an error itself.
2183 #[stable(feature = "rust1", since = "1.0.0")]
2184 impl<T: fmt::Display + ?Sized> ToString for T {
2186 default fn to_string(&self) -> String {
2188 let mut buf = String::new();
2189 buf.write_fmt(format_args!("{}", self))
2190 .expect("a Display implementation returned an error unexpectedly");
2191 buf.shrink_to_fit();
2196 #[stable(feature = "str_to_string_specialization", since = "1.9.0")]
2197 impl ToString for str {
2199 fn to_string(&self) -> String {
2204 #[stable(feature = "cow_str_to_string_specialization", since = "1.17.0")]
2205 impl ToString for Cow<'_, str> {
2207 fn to_string(&self) -> String {
2212 #[stable(feature = "string_to_string_specialization", since = "1.17.0")]
2213 impl ToString for String {
2215 fn to_string(&self) -> String {
2220 #[stable(feature = "rust1", since = "1.0.0")]
2221 impl AsRef<str> for String {
2223 fn as_ref(&self) -> &str {
2228 #[stable(feature = "string_as_mut", since = "1.43.0")]
2229 impl AsMut<str> for String {
2231 fn as_mut(&mut self) -> &mut str {
2236 #[stable(feature = "rust1", since = "1.0.0")]
2237 impl AsRef<[u8]> for String {
2239 fn as_ref(&self) -> &[u8] {
2244 #[stable(feature = "rust1", since = "1.0.0")]
2245 impl From<&str> for String {
2247 fn from(s: &str) -> String {
2252 #[stable(feature = "from_mut_str_for_string", since = "1.44.0")]
2253 impl From<&mut str> for String {
2254 /// Converts a `&mut str` into a `String`.
2256 /// The result is allocated on the heap.
2258 fn from(s: &mut str) -> String {
2263 #[stable(feature = "from_ref_string", since = "1.35.0")]
2264 impl From<&String> for String {
2266 fn from(s: &String) -> String {
2271 // note: test pulls in libstd, which causes errors here
2273 #[stable(feature = "string_from_box", since = "1.18.0")]
2274 impl From<Box<str>> for String {
2275 /// Converts the given boxed `str` slice to a `String`.
2276 /// It is notable that the `str` slice is owned.
2283 /// let s1: String = String::from("hello world");
2284 /// let s2: Box<str> = s1.into_boxed_str();
2285 /// let s3: String = String::from(s2);
2287 /// assert_eq!("hello world", s3)
2289 fn from(s: Box<str>) -> String {
2294 #[stable(feature = "box_from_str", since = "1.20.0")]
2295 impl From<String> for Box<str> {
2296 /// Converts the given `String` to a boxed `str` slice that is owned.
2303 /// let s1: String = String::from("hello world");
2304 /// let s2: Box<str> = Box::from(s1);
2305 /// let s3: String = String::from(s2);
2307 /// assert_eq!("hello world", s3)
2309 fn from(s: String) -> Box<str> {
2314 #[stable(feature = "string_from_cow_str", since = "1.14.0")]
2315 impl<'a> From<Cow<'a, str>> for String {
2316 fn from(s: Cow<'a, str>) -> String {
2321 #[stable(feature = "rust1", since = "1.0.0")]
2322 impl<'a> From<&'a str> for Cow<'a, str> {
2324 fn from(s: &'a str) -> Cow<'a, str> {
2329 #[stable(feature = "rust1", since = "1.0.0")]
2330 impl<'a> From<String> for Cow<'a, str> {
2332 fn from(s: String) -> Cow<'a, str> {
2337 #[stable(feature = "cow_from_string_ref", since = "1.28.0")]
2338 impl<'a> From<&'a String> for Cow<'a, str> {
2340 fn from(s: &'a String) -> Cow<'a, str> {
2341 Cow::Borrowed(s.as_str())
2345 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2346 impl<'a> FromIterator<char> for Cow<'a, str> {
2347 fn from_iter<I: IntoIterator<Item = char>>(it: I) -> Cow<'a, str> {
2348 Cow::Owned(FromIterator::from_iter(it))
2352 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2353 impl<'a, 'b> FromIterator<&'b str> for Cow<'a, str> {
2354 fn from_iter<I: IntoIterator<Item = &'b str>>(it: I) -> Cow<'a, str> {
2355 Cow::Owned(FromIterator::from_iter(it))
2359 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2360 impl<'a> FromIterator<String> for Cow<'a, str> {
2361 fn from_iter<I: IntoIterator<Item = String>>(it: I) -> Cow<'a, str> {
2362 Cow::Owned(FromIterator::from_iter(it))
2366 #[stable(feature = "from_string_for_vec_u8", since = "1.14.0")]
2367 impl From<String> for Vec<u8> {
2368 /// Converts the given `String` to a vector `Vec` that holds values of type `u8`.
2375 /// let s1 = String::from("hello world");
2376 /// let v1 = Vec::from(s1);
2379 /// println!("{}", b);
2382 fn from(string: String) -> Vec<u8> {
2387 #[stable(feature = "rust1", since = "1.0.0")]
2388 impl fmt::Write for String {
2390 fn write_str(&mut self, s: &str) -> fmt::Result {
2396 fn write_char(&mut self, c: char) -> fmt::Result {
2402 /// A draining iterator for `String`.
2404 /// This struct is created by the [`drain`] method on [`String`]. See its
2405 /// documentation for more.
2407 /// [`drain`]: struct.String.html#method.drain
2408 /// [`String`]: struct.String.html
2409 #[stable(feature = "drain", since = "1.6.0")]
2410 pub struct Drain<'a> {
2411 /// Will be used as &'a mut String in the destructor
2412 string: *mut String,
2413 /// Start of part to remove
2415 /// End of part to remove
2417 /// Current remaining range to remove
2421 #[stable(feature = "collection_debug", since = "1.17.0")]
2422 impl fmt::Debug for Drain<'_> {
2423 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2424 f.pad("Drain { .. }")
2428 #[stable(feature = "drain", since = "1.6.0")]
2429 unsafe impl Sync for Drain<'_> {}
2430 #[stable(feature = "drain", since = "1.6.0")]
2431 unsafe impl Send for Drain<'_> {}
2433 #[stable(feature = "drain", since = "1.6.0")]
2434 impl Drop for Drain<'_> {
2435 fn drop(&mut self) {
2437 // Use Vec::drain. "Reaffirm" the bounds checks to avoid
2438 // panic code being inserted again.
2439 let self_vec = (*self.string).as_mut_vec();
2440 if self.start <= self.end && self.end <= self_vec.len() {
2441 self_vec.drain(self.start..self.end);
2447 #[stable(feature = "drain", since = "1.6.0")]
2448 impl Iterator for Drain<'_> {
2452 fn next(&mut self) -> Option<char> {
2456 fn size_hint(&self) -> (usize, Option<usize>) {
2457 self.iter.size_hint()
2461 fn last(mut self) -> Option<char> {
2466 #[stable(feature = "drain", since = "1.6.0")]
2467 impl DoubleEndedIterator for Drain<'_> {
2469 fn next_back(&mut self) -> Option<char> {
2470 self.iter.next_back()
2474 #[stable(feature = "fused", since = "1.26.0")]
2475 impl FusedIterator for Drain<'_> {}