1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! A UTF-8 encoded, growable string.
13 //! This module contains the [`String`] type, a trait for converting
14 //! [`ToString`]s, and several error types that may result from working with
17 //! [`ToString`]: trait.ToString.html
21 //! There are multiple ways to create a new [`String`] from a string literal:
24 //! let s = "Hello".to_string();
26 //! let s = String::from("world");
27 //! let s: String = "also this".into();
30 //! You can create a new [`String`] from an existing one by concatenating with
33 //! [`String`]: struct.String.html
36 //! let s = "Hello".to_string();
38 //! let message = s + " world!";
41 //! If you have a vector of valid UTF-8 bytes, you can make a [`String`] out of
42 //! it. You can do the reverse too.
45 //! let sparkle_heart = vec![240, 159, 146, 150];
47 //! // We know these bytes are valid, so we'll use `unwrap()`.
48 //! let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
50 //! assert_eq!("💖", sparkle_heart);
52 //! let bytes = sparkle_heart.into_bytes();
54 //! assert_eq!(bytes, [240, 159, 146, 150]);
57 #![stable(feature = "rust1", since = "1.0.0")]
59 use core::char::{decode_utf16, REPLACEMENT_CHARACTER};
62 use core::iter::{FromIterator, FusedIterator};
63 use core::ops::Bound::{Excluded, Included, Unbounded};
64 use core::ops::{self, Add, AddAssign, Index, IndexMut, RangeBounds};
66 use core::str::pattern::Pattern;
69 use collections::CollectionAllocErr;
70 use borrow::{Cow, ToOwned};
72 use str::{self, from_boxed_utf8_unchecked, FromStr, Utf8Error, Chars};
75 /// A UTF-8 encoded, growable string.
77 /// The `String` type is the most common string type that has ownership over the
78 /// contents of the string. It has a close relationship with its borrowed
79 /// counterpart, the primitive [`str`].
81 /// [`str`]: ../../std/primitive.str.html
85 /// You can create a `String` from a literal string with [`String::from`]:
88 /// let hello = String::from("Hello, world!");
91 /// You can append a [`char`] to a `String` with the [`push`] method, and
92 /// append a [`&str`] with the [`push_str`] method:
95 /// let mut hello = String::from("Hello, ");
98 /// hello.push_str("orld!");
101 /// [`String::from`]: #method.from
102 /// [`char`]: ../../std/primitive.char.html
103 /// [`push`]: #method.push
104 /// [`push_str`]: #method.push_str
106 /// If you have a vector of UTF-8 bytes, you can create a `String` from it with
107 /// the [`from_utf8`] method:
110 /// // some bytes, in a vector
111 /// let sparkle_heart = vec![240, 159, 146, 150];
113 /// // We know these bytes are valid, so we'll use `unwrap()`.
114 /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
116 /// assert_eq!("💖", sparkle_heart);
119 /// [`from_utf8`]: #method.from_utf8
123 /// `String`s are always valid UTF-8. This has a few implications, the first of
124 /// which is that if you need a non-UTF-8 string, consider [`OsString`]. It is
125 /// similar, but without the UTF-8 constraint. The second implication is that
126 /// you cannot index into a `String`:
128 /// ```compile_fail,E0277
131 /// println!("The first letter of s is {}", s[0]); // ERROR!!!
134 /// [`OsString`]: ../../std/ffi/struct.OsString.html
136 /// Indexing is intended to be a constant-time operation, but UTF-8 encoding
137 /// does not allow us to do this. Furthermore, it's not clear what sort of
138 /// thing the index should return: a byte, a codepoint, or a grapheme cluster.
139 /// The [`bytes`] and [`chars`] methods return iterators over the first
140 /// two, respectively.
142 /// [`bytes`]: #method.bytes
143 /// [`chars`]: #method.chars
147 /// `String`s implement [`Deref`]`<Target=str>`, and so inherit all of [`str`]'s
148 /// methods. In addition, this means that you can pass a `String` to a
149 /// function which takes a [`&str`] by using an ampersand (`&`):
152 /// fn takes_str(s: &str) { }
154 /// let s = String::from("Hello");
159 /// This will create a [`&str`] from the `String` and pass it in. This
160 /// conversion is very inexpensive, and so generally, functions will accept
161 /// [`&str`]s as arguments unless they need a `String` for some specific
164 /// In certain cases Rust doesn't have enough information to make this
165 /// conversion, known as [`Deref`] coercion. In the following example a string
166 /// slice [`&'a str`][`&str`] implements the trait `TraitExample`, and the function
167 /// `example_func` takes anything that implements the trait. In this case Rust
168 /// would need to make two implicit conversions, which Rust doesn't have the
169 /// means to do. For that reason, the following example will not compile.
171 /// ```compile_fail,E0277
172 /// trait TraitExample {}
174 /// impl<'a> TraitExample for &'a str {}
176 /// fn example_func<A: TraitExample>(example_arg: A) {}
179 /// let example_string = String::from("example_string");
180 /// example_func(&example_string);
184 /// There are two options that would work instead. The first would be to
185 /// change the line `example_func(&example_string);` to
186 /// `example_func(example_string.as_str());`, using the method [`as_str()`]
187 /// to explicitly extract the string slice containing the string. The second
188 /// way changes `example_func(&example_string);` to
189 /// `example_func(&*example_string);`. In this case we are dereferencing a
190 /// `String` to a [`str`][`&str`], then referencing the [`str`][`&str`] back to
191 /// [`&str`]. The second way is more idiomatic, however both work to do the
192 /// conversion explicitly rather than relying on the implicit conversion.
196 /// A `String` is made up of three components: a pointer to some bytes, a
197 /// length, and a capacity. The pointer points to an internal buffer `String`
198 /// uses to store its data. The length is the number of bytes currently stored
199 /// in the buffer, and the capacity is the size of the buffer in bytes. As such,
200 /// the length will always be less than or equal to the capacity.
202 /// This buffer is always stored on the heap.
204 /// You can look at these with the [`as_ptr`], [`len`], and [`capacity`]
210 /// let story = String::from("Once upon a time...");
212 /// let ptr = story.as_ptr();
213 /// let len = story.len();
214 /// let capacity = story.capacity();
216 /// // story has nineteen bytes
217 /// assert_eq!(19, len);
219 /// // Now that we have our parts, we throw the story away.
220 /// mem::forget(story);
222 /// // We can re-build a String out of ptr, len, and capacity. This is all
223 /// // unsafe because we are responsible for making sure the components are
225 /// let s = unsafe { String::from_raw_parts(ptr as *mut _, len, capacity) } ;
227 /// assert_eq!(String::from("Once upon a time..."), s);
230 /// [`as_ptr`]: #method.as_ptr
231 /// [`len`]: #method.len
232 /// [`capacity`]: #method.capacity
234 /// If a `String` has enough capacity, adding elements to it will not
235 /// re-allocate. For example, consider this program:
238 /// let mut s = String::new();
240 /// println!("{}", s.capacity());
243 /// s.push_str("hello");
244 /// println!("{}", s.capacity());
248 /// This will output the following:
259 /// At first, we have no memory allocated at all, but as we append to the
260 /// string, it increases its capacity appropriately. If we instead use the
261 /// [`with_capacity`] method to allocate the correct capacity initially:
264 /// let mut s = String::with_capacity(25);
266 /// println!("{}", s.capacity());
269 /// s.push_str("hello");
270 /// println!("{}", s.capacity());
274 /// [`with_capacity`]: #method.with_capacity
276 /// We end up with a different output:
287 /// Here, there's no need to allocate more memory inside the loop.
289 /// [`&str`]: ../../std/primitive.str.html
290 /// [`Deref`]: ../../std/ops/trait.Deref.html
291 /// [`as_str()`]: struct.String.html#method.as_str
292 #[derive(PartialOrd, Eq, Ord)]
293 #[stable(feature = "rust1", since = "1.0.0")]
298 /// A possible error value when converting a `String` from a UTF-8 byte vector.
300 /// This type is the error type for the [`from_utf8`] method on [`String`]. It
301 /// is designed in such a way to carefully avoid reallocations: the
302 /// [`into_bytes`] method will give back the byte vector that was used in the
303 /// conversion attempt.
305 /// [`from_utf8`]: struct.String.html#method.from_utf8
306 /// [`String`]: struct.String.html
307 /// [`into_bytes`]: struct.FromUtf8Error.html#method.into_bytes
309 /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
310 /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
311 /// an analogue to `FromUtf8Error`, and you can get one from a `FromUtf8Error`
312 /// through the [`utf8_error`] method.
314 /// [`Utf8Error`]: ../../std/str/struct.Utf8Error.html
315 /// [`std::str`]: ../../std/str/index.html
316 /// [`u8`]: ../../std/primitive.u8.html
317 /// [`&str`]: ../../std/primitive.str.html
318 /// [`utf8_error`]: #method.utf8_error
325 /// // some invalid bytes, in a vector
326 /// let bytes = vec![0, 159];
328 /// let value = String::from_utf8(bytes);
330 /// assert!(value.is_err());
331 /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
333 #[stable(feature = "rust1", since = "1.0.0")]
335 pub struct FromUtf8Error {
340 /// A possible error value when converting a `String` from a UTF-16 byte slice.
342 /// This type is the error type for the [`from_utf16`] method on [`String`].
344 /// [`from_utf16`]: struct.String.html#method.from_utf16
345 /// [`String`]: struct.String.html
352 /// // 𝄞mu<invalid>ic
353 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
354 /// 0xD800, 0x0069, 0x0063];
356 /// assert!(String::from_utf16(v).is_err());
358 #[stable(feature = "rust1", since = "1.0.0")]
360 pub struct FromUtf16Error(());
363 /// Creates a new empty `String`.
365 /// Given that the `String` is empty, this will not allocate any initial
366 /// buffer. While that means that this initial operation is very
367 /// inexpensive, it may cause excessive allocation later when you add
368 /// data. If you have an idea of how much data the `String` will hold,
369 /// consider the [`with_capacity`] method to prevent excessive
372 /// [`with_capacity`]: #method.with_capacity
379 /// let s = String::new();
382 #[stable(feature = "rust1", since = "1.0.0")]
383 #[rustc_const_unstable(feature = "const_string_new")]
384 pub const fn new() -> String {
385 String { vec: Vec::new() }
388 /// Creates a new empty `String` with a particular capacity.
390 /// `String`s have an internal buffer to hold their data. The capacity is
391 /// the length of that buffer, and can be queried with the [`capacity`]
392 /// method. This method creates an empty `String`, but one with an initial
393 /// buffer that can hold `capacity` bytes. This is useful when you may be
394 /// appending a bunch of data to the `String`, reducing the number of
395 /// reallocations it needs to do.
397 /// [`capacity`]: #method.capacity
399 /// If the given capacity is `0`, no allocation will occur, and this method
400 /// is identical to the [`new`] method.
402 /// [`new`]: #method.new
409 /// let mut s = String::with_capacity(10);
411 /// // The String contains no chars, even though it has capacity for more
412 /// assert_eq!(s.len(), 0);
414 /// // These are all done without reallocating...
415 /// let cap = s.capacity();
420 /// assert_eq!(s.capacity(), cap);
422 /// // ...but this may make the vector reallocate
426 #[stable(feature = "rust1", since = "1.0.0")]
427 pub fn with_capacity(capacity: usize) -> String {
428 String { vec: Vec::with_capacity(capacity) }
431 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
432 // required for this method definition, is not available. Since we don't
433 // require this method for testing purposes, I'll just stub it
434 // NB see the slice::hack module in slice.rs for more information
437 pub fn from_str(_: &str) -> String {
438 panic!("not available with cfg(test)");
441 /// Converts a vector of bytes to a `String`.
443 /// A string slice ([`&str`]) is made of bytes ([`u8`]), and a vector of bytes
444 /// ([`Vec<u8>`]) is made of bytes, so this function converts between the
445 /// two. Not all byte slices are valid `String`s, however: `String`
446 /// requires that it is valid UTF-8. `from_utf8()` checks to ensure that
447 /// the bytes are valid UTF-8, and then does the conversion.
449 /// If you are sure that the byte slice is valid UTF-8, and you don't want
450 /// to incur the overhead of the validity check, there is an unsafe version
451 /// of this function, [`from_utf8_unchecked`], which has the same behavior
452 /// but skips the check.
454 /// This method will take care to not copy the vector, for efficiency's
457 /// If you need a [`&str`] instead of a `String`, consider
458 /// [`str::from_utf8`].
460 /// The inverse of this method is [`as_bytes`].
464 /// Returns [`Err`] if the slice is not UTF-8 with a description as to why the
465 /// provided bytes are not UTF-8. The vector you moved in is also included.
472 /// // some bytes, in a vector
473 /// let sparkle_heart = vec![240, 159, 146, 150];
475 /// // We know these bytes are valid, so we'll use `unwrap()`.
476 /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
478 /// assert_eq!("💖", sparkle_heart);
484 /// // some invalid bytes, in a vector
485 /// let sparkle_heart = vec![0, 159, 146, 150];
487 /// assert!(String::from_utf8(sparkle_heart).is_err());
490 /// See the docs for [`FromUtf8Error`] for more details on what you can do
493 /// [`from_utf8_unchecked`]: struct.String.html#method.from_utf8_unchecked
494 /// [`&str`]: ../../std/primitive.str.html
495 /// [`u8`]: ../../std/primitive.u8.html
496 /// [`Vec<u8>`]: ../../std/vec/struct.Vec.html
497 /// [`str::from_utf8`]: ../../std/str/fn.from_utf8.html
498 /// [`as_bytes`]: struct.String.html#method.as_bytes
499 /// [`FromUtf8Error`]: struct.FromUtf8Error.html
500 /// [`Err`]: ../../stdresult/enum.Result.html#variant.Err
502 #[stable(feature = "rust1", since = "1.0.0")]
503 pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error> {
504 match str::from_utf8(&vec) {
505 Ok(..) => Ok(String { vec: vec }),
515 /// Converts a slice of bytes to a string, including invalid characters.
517 /// Strings are made of bytes ([`u8`]), and a slice of bytes
518 /// ([`&[u8]`][byteslice]) is made of bytes, so this function converts
519 /// between the two. Not all byte slices are valid strings, however: strings
520 /// are required to be valid UTF-8. During this conversion,
521 /// `from_utf8_lossy()` will replace any invalid UTF-8 sequences with
522 /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD], which looks like this: �
524 /// [`u8`]: ../../std/primitive.u8.html
525 /// [byteslice]: ../../std/primitive.slice.html
526 /// [U+FFFD]: ../char/constant.REPLACEMENT_CHARACTER.html
528 /// If you are sure that the byte slice is valid UTF-8, and you don't want
529 /// to incur the overhead of the conversion, there is an unsafe version
530 /// of this function, [`from_utf8_unchecked`], which has the same behavior
531 /// but skips the checks.
533 /// [`from_utf8_unchecked`]: struct.String.html#method.from_utf8_unchecked
535 /// This function returns a [`Cow<'a, str>`]. If our byte slice is invalid
536 /// UTF-8, then we need to insert the replacement characters, which will
537 /// change the size of the string, and hence, require a `String`. But if
538 /// it's already valid UTF-8, we don't need a new allocation. This return
539 /// type allows us to handle both cases.
541 /// [`Cow<'a, str>`]: ../../std/borrow/enum.Cow.html
548 /// // some bytes, in a vector
549 /// let sparkle_heart = vec![240, 159, 146, 150];
551 /// let sparkle_heart = String::from_utf8_lossy(&sparkle_heart);
553 /// assert_eq!("💖", sparkle_heart);
559 /// // some invalid bytes
560 /// let input = b"Hello \xF0\x90\x80World";
561 /// let output = String::from_utf8_lossy(input);
563 /// assert_eq!("Hello �World", output);
565 #[stable(feature = "rust1", since = "1.0.0")]
566 pub fn from_utf8_lossy<'a>(v: &'a [u8]) -> Cow<'a, str> {
567 let mut iter = lossy::Utf8Lossy::from_bytes(v).chunks();
569 let (first_valid, first_broken) = if let Some(chunk) = iter.next() {
570 let lossy::Utf8LossyChunk { valid, broken } = chunk;
571 if valid.len() == v.len() {
572 debug_assert!(broken.is_empty());
573 return Cow::Borrowed(valid);
577 return Cow::Borrowed("");
580 const REPLACEMENT: &'static str = "\u{FFFD}";
582 let mut res = String::with_capacity(v.len());
583 res.push_str(first_valid);
584 if !first_broken.is_empty() {
585 res.push_str(REPLACEMENT);
588 for lossy::Utf8LossyChunk { valid, broken } in iter {
590 if !broken.is_empty() {
591 res.push_str(REPLACEMENT);
598 /// Decode a UTF-16 encoded vector `v` into a `String`, returning [`Err`]
599 /// if `v` contains any invalid data.
601 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
609 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
610 /// 0x0073, 0x0069, 0x0063];
611 /// assert_eq!(String::from("𝄞music"),
612 /// String::from_utf16(v).unwrap());
614 /// // 𝄞mu<invalid>ic
615 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
616 /// 0xD800, 0x0069, 0x0063];
617 /// assert!(String::from_utf16(v).is_err());
619 #[stable(feature = "rust1", since = "1.0.0")]
620 pub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error> {
621 decode_utf16(v.iter().cloned()).collect::<Result<_, _>>().map_err(|_| FromUtf16Error(()))
624 /// Decode a UTF-16 encoded slice `v` into a `String`, replacing
625 /// invalid data with [the replacement character (`U+FFFD`)][U+FFFD].
627 /// Unlike [`from_utf8_lossy`] which returns a [`Cow<'a, str>`],
628 /// `from_utf16_lossy` returns a `String` since the UTF-16 to UTF-8
629 /// conversion requires a memory allocation.
631 /// [`from_utf8_lossy`]: #method.from_utf8_lossy
632 /// [`Cow<'a, str>`]: ../borrow/enum.Cow.html
633 /// [U+FFFD]: ../char/constant.REPLACEMENT_CHARACTER.html
640 /// // 𝄞mus<invalid>ic<invalid>
641 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
642 /// 0x0073, 0xDD1E, 0x0069, 0x0063,
645 /// assert_eq!(String::from("𝄞mus\u{FFFD}ic\u{FFFD}"),
646 /// String::from_utf16_lossy(v));
649 #[stable(feature = "rust1", since = "1.0.0")]
650 pub fn from_utf16_lossy(v: &[u16]) -> String {
651 decode_utf16(v.iter().cloned()).map(|r| r.unwrap_or(REPLACEMENT_CHARACTER)).collect()
654 /// Creates a new `String` from a length, capacity, and pointer.
658 /// This is highly unsafe, due to the number of invariants that aren't
661 /// * The memory at `ptr` needs to have been previously allocated by the
662 /// same allocator the standard library uses.
663 /// * `length` needs to be less than or equal to `capacity`.
664 /// * `capacity` needs to be the correct value.
666 /// Violating these may cause problems like corrupting the allocator's
667 /// internal data structures.
669 /// The ownership of `ptr` is effectively transferred to the
670 /// `String` which may then deallocate, reallocate or change the
671 /// contents of memory pointed to by the pointer at will. Ensure
672 /// that nothing else uses the pointer after calling this
683 /// let s = String::from("hello");
684 /// let ptr = s.as_ptr();
685 /// let len = s.len();
686 /// let capacity = s.capacity();
690 /// let s = String::from_raw_parts(ptr as *mut _, len, capacity);
692 /// assert_eq!(String::from("hello"), s);
696 #[stable(feature = "rust1", since = "1.0.0")]
697 pub unsafe fn from_raw_parts(buf: *mut u8, length: usize, capacity: usize) -> String {
698 String { vec: Vec::from_raw_parts(buf, length, capacity) }
701 /// Converts a vector of bytes to a `String` without checking that the
702 /// string contains valid UTF-8.
704 /// See the safe version, [`from_utf8`], for more details.
706 /// [`from_utf8`]: struct.String.html#method.from_utf8
710 /// This function is unsafe because it does not check that the bytes passed
711 /// to it are valid UTF-8. If this constraint is violated, it may cause
712 /// memory unsafety issues with future users of the `String`, as the rest of
713 /// the standard library assumes that `String`s are valid UTF-8.
720 /// // some bytes, in a vector
721 /// let sparkle_heart = vec![240, 159, 146, 150];
723 /// let sparkle_heart = unsafe {
724 /// String::from_utf8_unchecked(sparkle_heart)
727 /// assert_eq!("💖", sparkle_heart);
730 #[stable(feature = "rust1", since = "1.0.0")]
731 pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String {
732 String { vec: bytes }
735 /// Converts a `String` into a byte vector.
737 /// This consumes the `String`, so we do not need to copy its contents.
744 /// let s = String::from("hello");
745 /// let bytes = s.into_bytes();
747 /// assert_eq!(&[104, 101, 108, 108, 111][..], &bytes[..]);
750 #[stable(feature = "rust1", since = "1.0.0")]
751 pub fn into_bytes(self) -> Vec<u8> {
755 /// Extracts a string slice containing the entire string.
762 /// let s = String::from("foo");
764 /// assert_eq!("foo", s.as_str());
767 #[stable(feature = "string_as_str", since = "1.7.0")]
768 pub fn as_str(&self) -> &str {
772 /// Converts a `String` into a mutable string slice.
779 /// let mut s = String::from("foobar");
780 /// let s_mut_str = s.as_mut_str();
782 /// s_mut_str.make_ascii_uppercase();
784 /// assert_eq!("FOOBAR", s_mut_str);
787 #[stable(feature = "string_as_str", since = "1.7.0")]
788 pub fn as_mut_str(&mut self) -> &mut str {
792 /// Appends a given string slice onto the end of this `String`.
799 /// let mut s = String::from("foo");
801 /// s.push_str("bar");
803 /// assert_eq!("foobar", s);
806 #[stable(feature = "rust1", since = "1.0.0")]
807 pub fn push_str(&mut self, string: &str) {
808 self.vec.extend_from_slice(string.as_bytes())
811 /// Returns this `String`'s capacity, in bytes.
818 /// let s = String::with_capacity(10);
820 /// assert!(s.capacity() >= 10);
823 #[stable(feature = "rust1", since = "1.0.0")]
824 pub fn capacity(&self) -> usize {
828 /// Ensures that this `String`'s capacity is at least `additional` bytes
829 /// larger than its length.
831 /// The capacity may be increased by more than `additional` bytes if it
832 /// chooses, to prevent frequent reallocations.
834 /// If you do not want this "at least" behavior, see the [`reserve_exact`]
839 /// Panics if the new capacity overflows [`usize`].
841 /// [`reserve_exact`]: struct.String.html#method.reserve_exact
842 /// [`usize`]: ../../std/primitive.usize.html
849 /// let mut s = String::new();
853 /// assert!(s.capacity() >= 10);
856 /// This may not actually increase the capacity:
859 /// let mut s = String::with_capacity(10);
863 /// // s now has a length of 2 and a capacity of 10
864 /// assert_eq!(2, s.len());
865 /// assert_eq!(10, s.capacity());
867 /// // Since we already have an extra 8 capacity, calling this...
870 /// // ... doesn't actually increase.
871 /// assert_eq!(10, s.capacity());
874 #[stable(feature = "rust1", since = "1.0.0")]
875 pub fn reserve(&mut self, additional: usize) {
876 self.vec.reserve(additional)
879 /// Ensures that this `String`'s capacity is `additional` bytes
880 /// larger than its length.
882 /// Consider using the [`reserve`] method unless you absolutely know
883 /// better than the allocator.
885 /// [`reserve`]: #method.reserve
889 /// Panics if the new capacity overflows `usize`.
896 /// let mut s = String::new();
898 /// s.reserve_exact(10);
900 /// assert!(s.capacity() >= 10);
903 /// This may not actually increase the capacity:
906 /// let mut s = String::with_capacity(10);
910 /// // s now has a length of 2 and a capacity of 10
911 /// assert_eq!(2, s.len());
912 /// assert_eq!(10, s.capacity());
914 /// // Since we already have an extra 8 capacity, calling this...
915 /// s.reserve_exact(8);
917 /// // ... doesn't actually increase.
918 /// assert_eq!(10, s.capacity());
921 #[stable(feature = "rust1", since = "1.0.0")]
922 pub fn reserve_exact(&mut self, additional: usize) {
923 self.vec.reserve_exact(additional)
926 /// Tries to reserve capacity for at least `additional` more elements to be inserted
927 /// in the given `String`. The collection may reserve more space to avoid
928 /// frequent reallocations. After calling `reserve`, capacity will be
929 /// greater than or equal to `self.len() + additional`. Does nothing if
930 /// capacity is already sufficient.
934 /// If the capacity overflows, or the allocator reports a failure, then an error
940 /// #![feature(try_reserve)]
941 /// use std::collections::CollectionAllocErr;
943 /// fn process_data(data: &str) -> Result<String, CollectionAllocErr> {
944 /// let mut output = String::new();
946 /// // Pre-reserve the memory, exiting if we can't
947 /// output.try_reserve(data.len())?;
949 /// // Now we know this can't OOM in the middle of our complex work
950 /// output.push_str(data);
954 /// # process_data("rust").expect("why is the test harness OOMing on 4 bytes?");
956 #[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
957 pub fn try_reserve(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
958 self.vec.try_reserve(additional)
961 /// Tries to reserves the minimum capacity for exactly `additional` more elements to
962 /// be inserted in the given `String`. After calling `reserve_exact`,
963 /// capacity will be greater than or equal to `self.len() + additional`.
964 /// Does nothing if the capacity is already sufficient.
966 /// Note that the allocator may give the collection more space than it
967 /// requests. Therefore capacity can not be relied upon to be precisely
968 /// minimal. Prefer `reserve` if future insertions are expected.
972 /// If the capacity overflows, or the allocator reports a failure, then an error
978 /// #![feature(try_reserve)]
979 /// use std::collections::CollectionAllocErr;
981 /// fn process_data(data: &str) -> Result<String, CollectionAllocErr> {
982 /// let mut output = String::new();
984 /// // Pre-reserve the memory, exiting if we can't
985 /// output.try_reserve(data.len())?;
987 /// // Now we know this can't OOM in the middle of our complex work
988 /// output.push_str(data);
992 /// # process_data("rust").expect("why is the test harness OOMing on 4 bytes?");
994 #[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
995 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
996 self.vec.try_reserve_exact(additional)
999 /// Shrinks the capacity of this `String` to match its length.
1006 /// let mut s = String::from("foo");
1009 /// assert!(s.capacity() >= 100);
1011 /// s.shrink_to_fit();
1012 /// assert_eq!(3, s.capacity());
1015 #[stable(feature = "rust1", since = "1.0.0")]
1016 pub fn shrink_to_fit(&mut self) {
1017 self.vec.shrink_to_fit()
1020 /// Shrinks the capacity of this `String` with a lower bound.
1022 /// The capacity will remain at least as large as both the length
1023 /// and the supplied value.
1025 /// Panics if the current capacity is smaller than the supplied
1026 /// minimum capacity.
1031 /// #![feature(shrink_to)]
1032 /// let mut s = String::from("foo");
1035 /// assert!(s.capacity() >= 100);
1037 /// s.shrink_to(10);
1038 /// assert!(s.capacity() >= 10);
1040 /// assert!(s.capacity() >= 3);
1043 #[unstable(feature = "shrink_to", reason = "new API", issue="0")]
1044 pub fn shrink_to(&mut self, min_capacity: usize) {
1045 self.vec.shrink_to(min_capacity)
1048 /// Appends the given [`char`] to the end of this `String`.
1050 /// [`char`]: ../../std/primitive.char.html
1057 /// let mut s = String::from("abc");
1063 /// assert_eq!("abc123", s);
1066 #[stable(feature = "rust1", since = "1.0.0")]
1067 pub fn push(&mut self, ch: char) {
1068 match ch.len_utf8() {
1069 1 => self.vec.push(ch as u8),
1070 _ => self.vec.extend_from_slice(ch.encode_utf8(&mut [0; 4]).as_bytes()),
1074 /// Returns a byte slice of this `String`'s contents.
1076 /// The inverse of this method is [`from_utf8`].
1078 /// [`from_utf8`]: #method.from_utf8
1085 /// let s = String::from("hello");
1087 /// assert_eq!(&[104, 101, 108, 108, 111], s.as_bytes());
1090 #[stable(feature = "rust1", since = "1.0.0")]
1091 pub fn as_bytes(&self) -> &[u8] {
1095 /// Shortens this `String` to the specified length.
1097 /// If `new_len` is greater than the string's current length, this has no
1100 /// Note that this method has no effect on the allocated capacity
1105 /// Panics if `new_len` does not lie on a [`char`] boundary.
1107 /// [`char`]: ../../std/primitive.char.html
1114 /// let mut s = String::from("hello");
1118 /// assert_eq!("he", s);
1121 #[stable(feature = "rust1", since = "1.0.0")]
1122 pub fn truncate(&mut self, new_len: usize) {
1123 if new_len <= self.len() {
1124 assert!(self.is_char_boundary(new_len));
1125 self.vec.truncate(new_len)
1129 /// Removes the last character from the string buffer and returns it.
1131 /// Returns [`None`] if this `String` is empty.
1133 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1140 /// let mut s = String::from("foo");
1142 /// assert_eq!(s.pop(), Some('o'));
1143 /// assert_eq!(s.pop(), Some('o'));
1144 /// assert_eq!(s.pop(), Some('f'));
1146 /// assert_eq!(s.pop(), None);
1149 #[stable(feature = "rust1", since = "1.0.0")]
1150 pub fn pop(&mut self) -> Option<char> {
1151 let ch = self.chars().rev().next()?;
1152 let newlen = self.len() - ch.len_utf8();
1154 self.vec.set_len(newlen);
1159 /// Removes a [`char`] from this `String` at a byte position and returns it.
1161 /// This is an `O(n)` operation, as it requires copying every element in the
1166 /// Panics if `idx` is larger than or equal to the `String`'s length,
1167 /// or if it does not lie on a [`char`] boundary.
1169 /// [`char`]: ../../std/primitive.char.html
1176 /// let mut s = String::from("foo");
1178 /// assert_eq!(s.remove(0), 'f');
1179 /// assert_eq!(s.remove(1), 'o');
1180 /// assert_eq!(s.remove(0), 'o');
1183 #[stable(feature = "rust1", since = "1.0.0")]
1184 pub fn remove(&mut self, idx: usize) -> char {
1185 let ch = match self[idx..].chars().next() {
1187 None => panic!("cannot remove a char from the end of a string"),
1190 let next = idx + ch.len_utf8();
1191 let len = self.len();
1193 ptr::copy(self.vec.as_ptr().offset(next as isize),
1194 self.vec.as_mut_ptr().offset(idx as isize),
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 and preserves the order of the retained
1210 /// let mut s = String::from("f_o_ob_ar");
1212 /// s.retain(|c| c != '_');
1214 /// assert_eq!(s, "foobar");
1217 #[stable(feature = "string_retain", since = "1.26.0")]
1218 pub fn retain<F>(&mut self, mut f: F)
1219 where F: FnMut(char) -> bool
1221 let len = self.len();
1222 let mut del_bytes = 0;
1227 self.get_unchecked(idx..len).chars().next().unwrap()
1229 let ch_len = ch.len_utf8();
1232 del_bytes += ch_len;
1233 } else if del_bytes > 0 {
1235 ptr::copy(self.vec.as_ptr().offset(idx as isize),
1236 self.vec.as_mut_ptr().offset((idx - del_bytes) as isize),
1241 // Point idx to the next char
1246 unsafe { self.vec.set_len(len - del_bytes); }
1250 /// Inserts a character into this `String` at a byte position.
1252 /// This is an `O(n)` operation as it requires copying every element in the
1257 /// Panics if `idx` is larger than the `String`'s length, or if it does not
1258 /// lie on a [`char`] boundary.
1260 /// [`char`]: ../../std/primitive.char.html
1267 /// let mut s = String::with_capacity(3);
1269 /// s.insert(0, 'f');
1270 /// s.insert(1, 'o');
1271 /// s.insert(2, 'o');
1273 /// assert_eq!("foo", s);
1276 #[stable(feature = "rust1", since = "1.0.0")]
1277 pub fn insert(&mut self, idx: usize, ch: char) {
1278 assert!(self.is_char_boundary(idx));
1279 let mut bits = [0; 4];
1280 let bits = ch.encode_utf8(&mut bits).as_bytes();
1283 self.insert_bytes(idx, bits);
1287 unsafe fn insert_bytes(&mut self, idx: usize, bytes: &[u8]) {
1288 let len = self.len();
1289 let amt = bytes.len();
1290 self.vec.reserve(amt);
1292 ptr::copy(self.vec.as_ptr().offset(idx as isize),
1293 self.vec.as_mut_ptr().offset((idx + amt) as isize),
1295 ptr::copy(bytes.as_ptr(),
1296 self.vec.as_mut_ptr().offset(idx as isize),
1298 self.vec.set_len(len + amt);
1301 /// Inserts a string slice into this `String` at a byte position.
1303 /// This is an `O(n)` operation as it requires copying every element in the
1308 /// Panics if `idx` is larger than the `String`'s length, or if it does not
1309 /// lie on a [`char`] boundary.
1311 /// [`char`]: ../../std/primitive.char.html
1318 /// let mut s = String::from("bar");
1320 /// s.insert_str(0, "foo");
1322 /// assert_eq!("foobar", s);
1325 #[stable(feature = "insert_str", since = "1.16.0")]
1326 pub fn insert_str(&mut self, idx: usize, string: &str) {
1327 assert!(self.is_char_boundary(idx));
1330 self.insert_bytes(idx, string.as_bytes());
1334 /// Returns a mutable reference to the contents of this `String`.
1338 /// This function is unsafe because it does not check that the bytes passed
1339 /// to it are valid UTF-8. If this constraint is violated, it may cause
1340 /// memory unsafety issues with future users of the `String`, as the rest of
1341 /// the standard library assumes that `String`s are valid UTF-8.
1348 /// let mut s = String::from("hello");
1351 /// let vec = s.as_mut_vec();
1352 /// assert_eq!(&[104, 101, 108, 108, 111][..], &vec[..]);
1356 /// assert_eq!(s, "olleh");
1359 #[stable(feature = "rust1", since = "1.0.0")]
1360 pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1364 /// Returns the length of this `String`, in bytes.
1371 /// let a = String::from("foo");
1373 /// assert_eq!(a.len(), 3);
1376 #[stable(feature = "rust1", since = "1.0.0")]
1377 pub fn len(&self) -> usize {
1381 /// Returns `true` if this `String` has a length of zero.
1383 /// Returns `false` otherwise.
1390 /// let mut v = String::new();
1391 /// assert!(v.is_empty());
1394 /// assert!(!v.is_empty());
1397 #[stable(feature = "rust1", since = "1.0.0")]
1398 pub fn is_empty(&self) -> bool {
1402 /// Splits the string into two at the given index.
1404 /// Returns a newly allocated `String`. `self` contains bytes `[0, at)`, and
1405 /// the returned `String` contains bytes `[at, len)`. `at` must be on the
1406 /// boundary of a UTF-8 code point.
1408 /// Note that the capacity of `self` does not change.
1412 /// Panics if `at` is not on a `UTF-8` code point boundary, or if it is beyond the last
1413 /// code point of the string.
1419 /// let mut hello = String::from("Hello, World!");
1420 /// let world = hello.split_off(7);
1421 /// assert_eq!(hello, "Hello, ");
1422 /// assert_eq!(world, "World!");
1426 #[stable(feature = "string_split_off", since = "1.16.0")]
1427 pub fn split_off(&mut self, at: usize) -> String {
1428 assert!(self.is_char_boundary(at));
1429 let other = self.vec.split_off(at);
1430 unsafe { String::from_utf8_unchecked(other) }
1433 /// Truncates this `String`, removing all contents.
1435 /// While this means the `String` will have a length of zero, it does not
1436 /// touch its capacity.
1443 /// let mut s = String::from("foo");
1447 /// assert!(s.is_empty());
1448 /// assert_eq!(0, s.len());
1449 /// assert_eq!(3, s.capacity());
1452 #[stable(feature = "rust1", since = "1.0.0")]
1453 pub fn clear(&mut self) {
1457 /// Creates a draining iterator that removes the specified range in the string
1458 /// and yields the removed chars.
1460 /// Note: The element range is removed even if the iterator is not
1461 /// consumed until the end.
1465 /// Panics if the starting point or end point do not lie on a [`char`]
1466 /// boundary, or if they're out of bounds.
1468 /// [`char`]: ../../std/primitive.char.html
1475 /// let mut s = String::from("α is alpha, β is beta");
1476 /// let beta_offset = s.find('β').unwrap_or(s.len());
1478 /// // Remove the range up until the β from the string
1479 /// let t: String = s.drain(..beta_offset).collect();
1480 /// assert_eq!(t, "α is alpha, ");
1481 /// assert_eq!(s, "β is beta");
1483 /// // A full range clears the string
1485 /// assert_eq!(s, "");
1487 #[stable(feature = "drain", since = "1.6.0")]
1488 pub fn drain<R>(&mut self, range: R) -> Drain
1489 where R: RangeBounds<usize>
1493 // The String version of Drain does not have the memory safety issues
1494 // of the vector version. The data is just plain bytes.
1495 // Because the range removal happens in Drop, if the Drain iterator is leaked,
1496 // the removal will not happen.
1497 let len = self.len();
1498 let start = match range.start_bound() {
1500 Excluded(&n) => n + 1,
1503 let end = match range.end_bound() {
1504 Included(&n) => n + 1,
1509 // Take out two simultaneous borrows. The &mut String won't be accessed
1510 // until iteration is over, in Drop.
1511 let self_ptr = self as *mut _;
1512 // slicing does the appropriate bounds checks
1513 let chars_iter = self[start..end].chars();
1523 /// Removes the specified range in the string,
1524 /// and replaces it with the given string.
1525 /// The given string doesn't need to be the same length as the range.
1529 /// Panics if the starting point or end point do not lie on a [`char`]
1530 /// boundary, or if they're out of bounds.
1532 /// [`char`]: ../../std/primitive.char.html
1533 /// [`Vec::splice`]: ../../std/vec/struct.Vec.html#method.splice
1540 /// let mut s = String::from("α is alpha, β is beta");
1541 /// let beta_offset = s.find('β').unwrap_or(s.len());
1543 /// // Replace the range up until the β from the string
1544 /// s.replace_range(..beta_offset, "Α is capital alpha; ");
1545 /// assert_eq!(s, "Α is capital alpha; β is beta");
1547 #[stable(feature = "splice", since = "1.27.0")]
1548 pub fn replace_range<R>(&mut self, range: R, replace_with: &str)
1549 where R: RangeBounds<usize>
1553 // Replace_range does not have the memory safety issues of a vector Splice.
1554 // of the vector version. The data is just plain bytes.
1556 match range.start_bound() {
1557 Included(&n) => assert!(self.is_char_boundary(n)),
1558 Excluded(&n) => assert!(self.is_char_boundary(n + 1)),
1561 match range.end_bound() {
1562 Included(&n) => assert!(self.is_char_boundary(n + 1)),
1563 Excluded(&n) => assert!(self.is_char_boundary(n)),
1569 }.splice(range, replace_with.bytes());
1572 /// Converts this `String` into a [`Box`]`<`[`str`]`>`.
1574 /// This will drop any excess capacity.
1576 /// [`Box`]: ../../std/boxed/struct.Box.html
1577 /// [`str`]: ../../std/primitive.str.html
1584 /// let s = String::from("hello");
1586 /// let b = s.into_boxed_str();
1588 #[stable(feature = "box_str", since = "1.4.0")]
1590 pub fn into_boxed_str(self) -> Box<str> {
1591 let slice = self.vec.into_boxed_slice();
1592 unsafe { from_boxed_utf8_unchecked(slice) }
1596 impl FromUtf8Error {
1597 /// Returns a slice of [`u8`]s bytes that were attempted to convert to a `String`.
1604 /// // some invalid bytes, in a vector
1605 /// let bytes = vec![0, 159];
1607 /// let value = String::from_utf8(bytes);
1609 /// assert_eq!(&[0, 159], value.unwrap_err().as_bytes());
1611 #[stable(feature = "from_utf8_error_as_bytes", since = "1.26.0")]
1612 pub fn as_bytes(&self) -> &[u8] {
1616 /// Returns the bytes that were attempted to convert to a `String`.
1618 /// This method is carefully constructed to avoid allocation. It will
1619 /// consume the error, moving out the bytes, so that a copy of the bytes
1620 /// does not need to be made.
1627 /// // some invalid bytes, in a vector
1628 /// let bytes = vec![0, 159];
1630 /// let value = String::from_utf8(bytes);
1632 /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
1634 #[stable(feature = "rust1", since = "1.0.0")]
1635 pub fn into_bytes(self) -> Vec<u8> {
1639 /// Fetch a `Utf8Error` to get more details about the conversion failure.
1641 /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
1642 /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
1643 /// an analogue to `FromUtf8Error`. See its documentation for more details
1646 /// [`Utf8Error`]: ../../std/str/struct.Utf8Error.html
1647 /// [`std::str`]: ../../std/str/index.html
1648 /// [`u8`]: ../../std/primitive.u8.html
1649 /// [`&str`]: ../../std/primitive.str.html
1656 /// // some invalid bytes, in a vector
1657 /// let bytes = vec![0, 159];
1659 /// let error = String::from_utf8(bytes).unwrap_err().utf8_error();
1661 /// // the first byte is invalid here
1662 /// assert_eq!(1, error.valid_up_to());
1664 #[stable(feature = "rust1", since = "1.0.0")]
1665 pub fn utf8_error(&self) -> Utf8Error {
1670 #[stable(feature = "rust1", since = "1.0.0")]
1671 impl fmt::Display for FromUtf8Error {
1672 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1673 fmt::Display::fmt(&self.error, f)
1677 #[stable(feature = "rust1", since = "1.0.0")]
1678 impl fmt::Display for FromUtf16Error {
1679 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1680 fmt::Display::fmt("invalid utf-16: lone surrogate found", f)
1684 #[stable(feature = "rust1", since = "1.0.0")]
1685 impl Clone for String {
1686 fn clone(&self) -> Self {
1687 String { vec: self.vec.clone() }
1690 fn clone_from(&mut self, source: &Self) {
1691 self.vec.clone_from(&source.vec);
1695 #[stable(feature = "rust1", since = "1.0.0")]
1696 impl FromIterator<char> for String {
1697 fn from_iter<I: IntoIterator<Item = char>>(iter: I) -> String {
1698 let mut buf = String::new();
1704 #[stable(feature = "string_from_iter_by_ref", since = "1.17.0")]
1705 impl<'a> FromIterator<&'a char> for String {
1706 fn from_iter<I: IntoIterator<Item = &'a char>>(iter: I) -> String {
1707 let mut buf = String::new();
1713 #[stable(feature = "rust1", since = "1.0.0")]
1714 impl<'a> FromIterator<&'a str> for String {
1715 fn from_iter<I: IntoIterator<Item = &'a str>>(iter: I) -> String {
1716 let mut buf = String::new();
1722 #[stable(feature = "extend_string", since = "1.4.0")]
1723 impl FromIterator<String> for String {
1724 fn from_iter<I: IntoIterator<Item = String>>(iter: I) -> String {
1725 let mut buf = String::new();
1731 #[stable(feature = "herd_cows", since = "1.19.0")]
1732 impl<'a> FromIterator<Cow<'a, str>> for String {
1733 fn from_iter<I: IntoIterator<Item = Cow<'a, str>>>(iter: I) -> String {
1734 let mut buf = String::new();
1740 #[stable(feature = "rust1", since = "1.0.0")]
1741 impl Extend<char> for String {
1742 fn extend<I: IntoIterator<Item = char>>(&mut self, iter: I) {
1743 let iterator = iter.into_iter();
1744 let (lower_bound, _) = iterator.size_hint();
1745 self.reserve(lower_bound);
1746 for ch in iterator {
1752 #[stable(feature = "extend_ref", since = "1.2.0")]
1753 impl<'a> Extend<&'a char> for String {
1754 fn extend<I: IntoIterator<Item = &'a char>>(&mut self, iter: I) {
1755 self.extend(iter.into_iter().cloned());
1759 #[stable(feature = "rust1", since = "1.0.0")]
1760 impl<'a> Extend<&'a str> for String {
1761 fn extend<I: IntoIterator<Item = &'a str>>(&mut self, iter: I) {
1768 #[stable(feature = "extend_string", since = "1.4.0")]
1769 impl Extend<String> for String {
1770 fn extend<I: IntoIterator<Item = String>>(&mut self, iter: I) {
1777 #[stable(feature = "herd_cows", since = "1.19.0")]
1778 impl<'a> Extend<Cow<'a, str>> for String {
1779 fn extend<I: IntoIterator<Item = Cow<'a, str>>>(&mut self, iter: I) {
1786 /// A convenience impl that delegates to the impl for `&str`
1787 #[unstable(feature = "pattern",
1788 reason = "API not fully fleshed out and ready to be stabilized",
1790 impl<'a, 'b> Pattern<'a> for &'b String {
1791 type Searcher = <&'b str as Pattern<'a>>::Searcher;
1793 fn into_searcher(self, haystack: &'a str) -> <&'b str as Pattern<'a>>::Searcher {
1794 self[..].into_searcher(haystack)
1798 fn is_contained_in(self, haystack: &'a str) -> bool {
1799 self[..].is_contained_in(haystack)
1803 fn is_prefix_of(self, haystack: &'a str) -> bool {
1804 self[..].is_prefix_of(haystack)
1808 #[stable(feature = "rust1", since = "1.0.0")]
1809 impl PartialEq for String {
1811 fn eq(&self, other: &String) -> bool {
1812 PartialEq::eq(&self[..], &other[..])
1815 fn ne(&self, other: &String) -> bool {
1816 PartialEq::ne(&self[..], &other[..])
1820 macro_rules! impl_eq {
1821 ($lhs:ty, $rhs: ty) => {
1822 #[stable(feature = "rust1", since = "1.0.0")]
1823 impl<'a, 'b> PartialEq<$rhs> for $lhs {
1825 fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
1827 fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
1830 #[stable(feature = "rust1", since = "1.0.0")]
1831 impl<'a, 'b> PartialEq<$lhs> for $rhs {
1833 fn eq(&self, other: &$lhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
1835 fn ne(&self, other: &$lhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
1841 impl_eq! { String, str }
1842 impl_eq! { String, &'a str }
1843 impl_eq! { Cow<'a, str>, str }
1844 impl_eq! { Cow<'a, str>, &'b str }
1845 impl_eq! { Cow<'a, str>, String }
1847 #[stable(feature = "rust1", since = "1.0.0")]
1848 impl Default for String {
1849 /// Creates an empty `String`.
1851 fn default() -> String {
1856 #[stable(feature = "rust1", since = "1.0.0")]
1857 impl fmt::Display for String {
1859 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1860 fmt::Display::fmt(&**self, f)
1864 #[stable(feature = "rust1", since = "1.0.0")]
1865 impl fmt::Debug for String {
1867 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1868 fmt::Debug::fmt(&**self, f)
1872 #[stable(feature = "rust1", since = "1.0.0")]
1873 impl hash::Hash for String {
1875 fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
1876 (**self).hash(hasher)
1880 /// Implements the `+` operator for concatenating two strings.
1882 /// This consumes the `String` on the left-hand side and re-uses its buffer (growing it if
1883 /// necessary). This is done to avoid allocating a new `String` and copying the entire contents on
1884 /// every operation, which would lead to `O(n^2)` running time when building an `n`-byte string by
1885 /// repeated concatenation.
1887 /// The string on the right-hand side is only borrowed; its contents are copied into the returned
1892 /// Concatenating two `String`s takes the first by value and borrows the second:
1895 /// let a = String::from("hello");
1896 /// let b = String::from(" world");
1898 /// // `a` is moved and can no longer be used here.
1901 /// If you want to keep using the first `String`, you can clone it and append to the clone instead:
1904 /// let a = String::from("hello");
1905 /// let b = String::from(" world");
1906 /// let c = a.clone() + &b;
1907 /// // `a` is still valid here.
1910 /// Concatenating `&str` slices can be done by converting the first to a `String`:
1913 /// let a = "hello";
1914 /// let b = " world";
1915 /// let c = a.to_string() + b;
1917 #[stable(feature = "rust1", since = "1.0.0")]
1918 impl<'a> Add<&'a str> for String {
1919 type Output = String;
1922 fn add(mut self, other: &str) -> String {
1923 self.push_str(other);
1928 /// Implements the `+=` operator for appending to a `String`.
1930 /// This has the same behavior as the [`push_str`] method.
1932 /// [`push_str`]: struct.String.html#method.push_str
1933 #[stable(feature = "stringaddassign", since = "1.12.0")]
1934 impl<'a> AddAssign<&'a str> for String {
1936 fn add_assign(&mut self, other: &str) {
1937 self.push_str(other);
1941 #[stable(feature = "rust1", since = "1.0.0")]
1942 impl ops::Index<ops::Range<usize>> for String {
1946 fn index(&self, index: ops::Range<usize>) -> &str {
1950 #[stable(feature = "rust1", since = "1.0.0")]
1951 impl ops::Index<ops::RangeTo<usize>> for String {
1955 fn index(&self, index: ops::RangeTo<usize>) -> &str {
1959 #[stable(feature = "rust1", since = "1.0.0")]
1960 impl ops::Index<ops::RangeFrom<usize>> for String {
1964 fn index(&self, index: ops::RangeFrom<usize>) -> &str {
1968 #[stable(feature = "rust1", since = "1.0.0")]
1969 impl ops::Index<ops::RangeFull> for String {
1973 fn index(&self, _index: ops::RangeFull) -> &str {
1974 unsafe { str::from_utf8_unchecked(&self.vec) }
1977 #[stable(feature = "inclusive_range", since = "1.26.0")]
1978 impl ops::Index<ops::RangeInclusive<usize>> for String {
1982 fn index(&self, index: ops::RangeInclusive<usize>) -> &str {
1983 Index::index(&**self, index)
1986 #[stable(feature = "inclusive_range", since = "1.26.0")]
1987 impl ops::Index<ops::RangeToInclusive<usize>> for String {
1991 fn index(&self, index: ops::RangeToInclusive<usize>) -> &str {
1992 Index::index(&**self, index)
1996 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
1997 impl ops::IndexMut<ops::Range<usize>> for String {
1999 fn index_mut(&mut self, index: ops::Range<usize>) -> &mut str {
2000 &mut self[..][index]
2003 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2004 impl ops::IndexMut<ops::RangeTo<usize>> for String {
2006 fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut str {
2007 &mut self[..][index]
2010 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2011 impl ops::IndexMut<ops::RangeFrom<usize>> for String {
2013 fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut str {
2014 &mut self[..][index]
2017 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2018 impl ops::IndexMut<ops::RangeFull> for String {
2020 fn index_mut(&mut self, _index: ops::RangeFull) -> &mut str {
2021 unsafe { str::from_utf8_unchecked_mut(&mut *self.vec) }
2024 #[stable(feature = "inclusive_range", since = "1.26.0")]
2025 impl ops::IndexMut<ops::RangeInclusive<usize>> for String {
2027 fn index_mut(&mut self, index: ops::RangeInclusive<usize>) -> &mut str {
2028 IndexMut::index_mut(&mut **self, index)
2031 #[stable(feature = "inclusive_range", since = "1.26.0")]
2032 impl ops::IndexMut<ops::RangeToInclusive<usize>> for String {
2034 fn index_mut(&mut self, index: ops::RangeToInclusive<usize>) -> &mut str {
2035 IndexMut::index_mut(&mut **self, index)
2039 #[stable(feature = "rust1", since = "1.0.0")]
2040 impl ops::Deref for String {
2044 fn deref(&self) -> &str {
2045 unsafe { str::from_utf8_unchecked(&self.vec) }
2049 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
2050 impl ops::DerefMut for String {
2052 fn deref_mut(&mut self) -> &mut str {
2053 unsafe { str::from_utf8_unchecked_mut(&mut *self.vec) }
2057 /// An error when parsing a `String`.
2059 /// This `enum` is slightly awkward: it will never actually exist. This error is
2060 /// part of the type signature of the implementation of [`FromStr`] on
2061 /// [`String`]. The return type of [`from_str`], requires that an error be
2062 /// defined, but, given that a [`String`] can always be made into a new
2063 /// [`String`] without error, this type will never actually be returned. As
2064 /// such, it is only here to satisfy said signature, and is useless otherwise.
2066 /// [`FromStr`]: ../../std/str/trait.FromStr.html
2067 /// [`String`]: struct.String.html
2068 /// [`from_str`]: ../../std/str/trait.FromStr.html#tymethod.from_str
2069 #[stable(feature = "str_parse_error", since = "1.5.0")]
2071 pub enum ParseError {}
2073 #[stable(feature = "rust1", since = "1.0.0")]
2074 impl FromStr for String {
2075 type Err = ParseError;
2077 fn from_str(s: &str) -> Result<String, ParseError> {
2082 #[stable(feature = "str_parse_error", since = "1.5.0")]
2083 impl Clone for ParseError {
2084 fn clone(&self) -> ParseError {
2089 #[stable(feature = "str_parse_error", since = "1.5.0")]
2090 impl fmt::Debug for ParseError {
2091 fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result {
2096 #[stable(feature = "str_parse_error2", since = "1.8.0")]
2097 impl fmt::Display for ParseError {
2098 fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result {
2103 #[stable(feature = "str_parse_error", since = "1.5.0")]
2104 impl PartialEq for ParseError {
2105 fn eq(&self, _: &ParseError) -> bool {
2110 #[stable(feature = "str_parse_error", since = "1.5.0")]
2111 impl Eq for ParseError {}
2113 /// A trait for converting a value to a `String`.
2115 /// This trait is automatically implemented for any type which implements the
2116 /// [`Display`] trait. As such, `ToString` shouldn't be implemented directly:
2117 /// [`Display`] should be implemented instead, and you get the `ToString`
2118 /// implementation for free.
2120 /// [`Display`]: ../../std/fmt/trait.Display.html
2121 #[stable(feature = "rust1", since = "1.0.0")]
2122 pub trait ToString {
2123 /// Converts the given value to a `String`.
2131 /// let five = String::from("5");
2133 /// assert_eq!(five, i.to_string());
2135 #[rustc_conversion_suggestion]
2136 #[stable(feature = "rust1", since = "1.0.0")]
2137 fn to_string(&self) -> String;
2142 /// In this implementation, the `to_string` method panics
2143 /// if the `Display` implementation returns an error.
2144 /// This indicates an incorrect `Display` implementation
2145 /// since `fmt::Write for String` never returns an error itself.
2146 #[stable(feature = "rust1", since = "1.0.0")]
2147 impl<T: fmt::Display + ?Sized> ToString for T {
2149 default fn to_string(&self) -> String {
2150 use core::fmt::Write;
2151 let mut buf = String::new();
2152 buf.write_fmt(format_args!("{}", self))
2153 .expect("a Display implementation return an error unexpectedly");
2154 buf.shrink_to_fit();
2159 #[stable(feature = "str_to_string_specialization", since = "1.9.0")]
2160 impl ToString for str {
2162 fn to_string(&self) -> String {
2167 #[stable(feature = "cow_str_to_string_specialization", since = "1.17.0")]
2168 impl<'a> ToString for Cow<'a, str> {
2170 fn to_string(&self) -> String {
2175 #[stable(feature = "string_to_string_specialization", since = "1.17.0")]
2176 impl ToString for String {
2178 fn to_string(&self) -> String {
2183 #[stable(feature = "rust1", since = "1.0.0")]
2184 impl AsRef<str> for String {
2186 fn as_ref(&self) -> &str {
2191 #[stable(feature = "rust1", since = "1.0.0")]
2192 impl AsRef<[u8]> for String {
2194 fn as_ref(&self) -> &[u8] {
2199 #[stable(feature = "rust1", since = "1.0.0")]
2200 impl<'a> From<&'a str> for String {
2201 fn from(s: &'a str) -> String {
2206 // note: test pulls in libstd, which causes errors here
2208 #[stable(feature = "string_from_box", since = "1.18.0")]
2209 impl From<Box<str>> for String {
2210 fn from(s: Box<str>) -> String {
2215 #[stable(feature = "box_from_str", since = "1.20.0")]
2216 impl From<String> for Box<str> {
2217 fn from(s: String) -> Box<str> {
2222 #[stable(feature = "string_from_cow_str", since = "1.14.0")]
2223 impl<'a> From<Cow<'a, str>> for String {
2224 fn from(s: Cow<'a, str>) -> String {
2229 #[stable(feature = "rust1", since = "1.0.0")]
2230 impl<'a> From<&'a str> for Cow<'a, str> {
2232 fn from(s: &'a str) -> Cow<'a, str> {
2237 #[stable(feature = "rust1", since = "1.0.0")]
2238 impl<'a> From<String> for Cow<'a, str> {
2240 fn from(s: String) -> Cow<'a, str> {
2245 #[stable(feature = "cow_from_string_ref", since = "1.28.0")]
2246 impl<'a> From<&'a String> for Cow<'a, str> {
2248 fn from(s: &'a String) -> Cow<'a, str> {
2249 Cow::Borrowed(s.as_str())
2253 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2254 impl<'a> FromIterator<char> for Cow<'a, str> {
2255 fn from_iter<I: IntoIterator<Item = char>>(it: I) -> Cow<'a, str> {
2256 Cow::Owned(FromIterator::from_iter(it))
2260 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2261 impl<'a, 'b> FromIterator<&'b str> for Cow<'a, str> {
2262 fn from_iter<I: IntoIterator<Item = &'b str>>(it: I) -> Cow<'a, str> {
2263 Cow::Owned(FromIterator::from_iter(it))
2267 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2268 impl<'a> FromIterator<String> for Cow<'a, str> {
2269 fn from_iter<I: IntoIterator<Item = String>>(it: I) -> Cow<'a, str> {
2270 Cow::Owned(FromIterator::from_iter(it))
2274 #[stable(feature = "from_string_for_vec_u8", since = "1.14.0")]
2275 impl From<String> for Vec<u8> {
2276 fn from(string: String) -> Vec<u8> {
2281 #[stable(feature = "rust1", since = "1.0.0")]
2282 impl fmt::Write for String {
2284 fn write_str(&mut self, s: &str) -> fmt::Result {
2290 fn write_char(&mut self, c: char) -> fmt::Result {
2296 /// A draining iterator for `String`.
2298 /// This struct is created by the [`drain`] method on [`String`]. See its
2299 /// documentation for more.
2301 /// [`drain`]: struct.String.html#method.drain
2302 /// [`String`]: struct.String.html
2303 #[stable(feature = "drain", since = "1.6.0")]
2304 pub struct Drain<'a> {
2305 /// Will be used as &'a mut String in the destructor
2306 string: *mut String,
2307 /// Start of part to remove
2309 /// End of part to remove
2311 /// Current remaining range to remove
2315 #[stable(feature = "collection_debug", since = "1.17.0")]
2316 impl<'a> fmt::Debug for Drain<'a> {
2317 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2318 f.pad("Drain { .. }")
2322 #[stable(feature = "drain", since = "1.6.0")]
2323 unsafe impl<'a> Sync for Drain<'a> {}
2324 #[stable(feature = "drain", since = "1.6.0")]
2325 unsafe impl<'a> Send for Drain<'a> {}
2327 #[stable(feature = "drain", since = "1.6.0")]
2328 impl<'a> Drop for Drain<'a> {
2329 fn drop(&mut self) {
2331 // Use Vec::drain. "Reaffirm" the bounds checks to avoid
2332 // panic code being inserted again.
2333 let self_vec = (*self.string).as_mut_vec();
2334 if self.start <= self.end && self.end <= self_vec.len() {
2335 self_vec.drain(self.start..self.end);
2341 #[stable(feature = "drain", since = "1.6.0")]
2342 impl<'a> Iterator for Drain<'a> {
2346 fn next(&mut self) -> Option<char> {
2350 fn size_hint(&self) -> (usize, Option<usize>) {
2351 self.iter.size_hint()
2355 #[stable(feature = "drain", since = "1.6.0")]
2356 impl<'a> DoubleEndedIterator for Drain<'a> {
2358 fn next_back(&mut self) -> Option<char> {
2359 self.iter.next_back()
2363 #[stable(feature = "fused", since = "1.26.0")]
2364 impl<'a> FusedIterator for Drain<'a> {}