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")]
61 use core::iter::{FromIterator, FusedIterator};
62 use core::ops::{self, Add, AddAssign, Index, IndexMut};
64 use core::str::pattern::Pattern;
65 use std_unicode::lossy;
66 use std_unicode::char::{decode_utf16, REPLACEMENT_CHARACTER};
68 use borrow::{Cow, ToOwned};
69 use range::RangeArgument;
70 use Bound::{Excluded, Included, Unbounded};
71 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 pub fn new() -> String {
384 String { vec: Vec::new() }
387 /// Creates a new empty `String` with a particular capacity.
389 /// `String`s have an internal buffer to hold their data. The capacity is
390 /// the length of that buffer, and can be queried with the [`capacity`]
391 /// method. This method creates an empty `String`, but one with an initial
392 /// buffer that can hold `capacity` bytes. This is useful when you may be
393 /// appending a bunch of data to the `String`, reducing the number of
394 /// reallocations it needs to do.
396 /// [`capacity`]: #method.capacity
398 /// If the given capacity is `0`, no allocation will occur, and this method
399 /// is identical to the [`new`] method.
401 /// [`new`]: #method.new
408 /// let mut s = String::with_capacity(10);
410 /// // The String contains no chars, even though it has capacity for more
411 /// assert_eq!(s.len(), 0);
413 /// // These are all done without reallocating...
414 /// let cap = s.capacity();
419 /// assert_eq!(s.capacity(), cap);
421 /// // ...but this may make the vector reallocate
425 #[stable(feature = "rust1", since = "1.0.0")]
426 pub fn with_capacity(capacity: usize) -> String {
427 String { vec: Vec::with_capacity(capacity) }
430 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
431 // required for this method definition, is not available. Since we don't
432 // require this method for testing purposes, I'll just stub it
433 // NB see the slice::hack module in slice.rs for more information
436 pub fn from_str(_: &str) -> String {
437 panic!("not available with cfg(test)");
440 /// Converts a vector of bytes to a `String`.
442 /// A string slice ([`&str`]) is made of bytes ([`u8`]), and a vector of bytes
443 /// ([`Vec<u8>`]) is made of bytes, so this function converts between the
444 /// two. Not all byte slices are valid `String`s, however: `String`
445 /// requires that it is valid UTF-8. `from_utf8()` checks to ensure that
446 /// the bytes are valid UTF-8, and then does the conversion.
448 /// If you are sure that the byte slice is valid UTF-8, and you don't want
449 /// to incur the overhead of the validity check, there is an unsafe version
450 /// of this function, [`from_utf8_unchecked`], which has the same behavior
451 /// but skips the check.
453 /// This method will take care to not copy the vector, for efficiency's
456 /// If you need a [`&str`] instead of a `String`, consider
457 /// [`str::from_utf8`].
459 /// The inverse of this method is [`as_bytes`].
463 /// Returns [`Err`] if the slice is not UTF-8 with a description as to why the
464 /// provided bytes are not UTF-8. The vector you moved in is also included.
471 /// // some bytes, in a vector
472 /// let sparkle_heart = vec![240, 159, 146, 150];
474 /// // We know these bytes are valid, so we'll use `unwrap()`.
475 /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
477 /// assert_eq!("💖", sparkle_heart);
483 /// // some invalid bytes, in a vector
484 /// let sparkle_heart = vec![0, 159, 146, 150];
486 /// assert!(String::from_utf8(sparkle_heart).is_err());
489 /// See the docs for [`FromUtf8Error`] for more details on what you can do
492 /// [`from_utf8_unchecked`]: struct.String.html#method.from_utf8_unchecked
493 /// [`&str`]: ../../std/primitive.str.html
494 /// [`u8`]: ../../std/primitive.u8.html
495 /// [`Vec<u8>`]: ../../std/vec/struct.Vec.html
496 /// [`str::from_utf8`]: ../../std/str/fn.from_utf8.html
497 /// [`as_bytes`]: struct.String.html#method.as_bytes
498 /// [`FromUtf8Error`]: struct.FromUtf8Error.html
499 /// [`Err`]: ../../stdresult/enum.Result.html#variant.Err
501 #[stable(feature = "rust1", since = "1.0.0")]
502 pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error> {
503 match str::from_utf8(&vec) {
504 Ok(..) => Ok(String { vec: vec }),
514 /// Converts a slice of bytes to a string, including invalid characters.
516 /// Strings are made of bytes ([`u8`]), and a slice of bytes
517 /// ([`&[u8]`][byteslice]) is made of bytes, so this function converts
518 /// between the two. Not all byte slices are valid strings, however: strings
519 /// are required to be valid UTF-8. During this conversion,
520 /// `from_utf8_lossy()` will replace any invalid UTF-8 sequences with
521 /// `U+FFFD REPLACEMENT CHARACTER`, which looks like this: �
523 /// [`u8`]: ../../std/primitive.u8.html
524 /// [byteslice]: ../../std/primitive.slice.html
526 /// If you are sure that the byte slice is valid UTF-8, and you don't want
527 /// to incur the overhead of the conversion, there is an unsafe version
528 /// of this function, [`from_utf8_unchecked`], which has the same behavior
529 /// but skips the checks.
531 /// [`from_utf8_unchecked`]: struct.String.html#method.from_utf8_unchecked
533 /// This function returns a [`Cow<'a, str>`]. If our byte slice is invalid
534 /// UTF-8, then we need to insert the replacement characters, which will
535 /// change the size of the string, and hence, require a `String`. But if
536 /// it's already valid UTF-8, we don't need a new allocation. This return
537 /// type allows us to handle both cases.
539 /// [`Cow<'a, str>`]: ../../std/borrow/enum.Cow.html
546 /// // some bytes, in a vector
547 /// let sparkle_heart = vec![240, 159, 146, 150];
549 /// let sparkle_heart = String::from_utf8_lossy(&sparkle_heart);
551 /// assert_eq!("💖", sparkle_heart);
557 /// // some invalid bytes
558 /// let input = b"Hello \xF0\x90\x80World";
559 /// let output = String::from_utf8_lossy(input);
561 /// assert_eq!("Hello �World", output);
563 #[stable(feature = "rust1", since = "1.0.0")]
564 pub fn from_utf8_lossy<'a>(v: &'a [u8]) -> Cow<'a, str> {
565 let mut iter = lossy::Utf8Lossy::from_bytes(v).chunks();
567 let (first_valid, first_broken) = if let Some(chunk) = iter.next() {
568 let lossy::Utf8LossyChunk { valid, broken } = chunk;
569 if valid.len() == v.len() {
570 debug_assert!(broken.is_empty());
571 return Cow::Borrowed(valid);
575 return Cow::Borrowed("");
578 const REPLACEMENT: &'static str = "\u{FFFD}";
580 let mut res = String::with_capacity(v.len());
581 res.push_str(first_valid);
582 if !first_broken.is_empty() {
583 res.push_str(REPLACEMENT);
586 for lossy::Utf8LossyChunk { valid, broken } in iter {
588 if !broken.is_empty() {
589 res.push_str(REPLACEMENT);
596 /// Decode a UTF-16 encoded vector `v` into a `String`, returning [`Err`]
597 /// if `v` contains any invalid data.
599 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
607 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
608 /// 0x0073, 0x0069, 0x0063];
609 /// assert_eq!(String::from("𝄞music"),
610 /// String::from_utf16(v).unwrap());
612 /// // 𝄞mu<invalid>ic
613 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
614 /// 0xD800, 0x0069, 0x0063];
615 /// assert!(String::from_utf16(v).is_err());
617 #[stable(feature = "rust1", since = "1.0.0")]
618 pub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error> {
619 decode_utf16(v.iter().cloned()).collect::<Result<_, _>>().map_err(|_| FromUtf16Error(()))
622 /// Decode a UTF-16 encoded slice `v` into a `String`, replacing
623 /// invalid data with the replacement character (U+FFFD).
625 /// Unlike [`from_utf8_lossy`] which returns a [`Cow<'a, str>`],
626 /// `from_utf16_lossy` returns a `String` since the UTF-16 to UTF-8
627 /// conversion requires a memory allocation.
629 /// [`from_utf8_lossy`]: #method.from_utf8_lossy
630 /// [`Cow<'a, str>`]: ../borrow/enum.Cow.html
637 /// // 𝄞mus<invalid>ic<invalid>
638 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
639 /// 0x0073, 0xDD1E, 0x0069, 0x0063,
642 /// assert_eq!(String::from("𝄞mus\u{FFFD}ic\u{FFFD}"),
643 /// String::from_utf16_lossy(v));
646 #[stable(feature = "rust1", since = "1.0.0")]
647 pub fn from_utf16_lossy(v: &[u16]) -> String {
648 decode_utf16(v.iter().cloned()).map(|r| r.unwrap_or(REPLACEMENT_CHARACTER)).collect()
651 /// Creates a new `String` from a length, capacity, and pointer.
655 /// This is highly unsafe, due to the number of invariants that aren't
658 /// * The memory at `ptr` needs to have been previously allocated by the
659 /// same allocator the standard library uses.
660 /// * `length` needs to be less than or equal to `capacity`.
661 /// * `capacity` needs to be the correct value.
663 /// Violating these may cause problems like corrupting the allocator's
664 /// internal data structures.
666 /// The ownership of `ptr` is effectively transferred to the
667 /// `String` which may then deallocate, reallocate or change the
668 /// contents of memory pointed to by the pointer at will. Ensure
669 /// that nothing else uses the pointer after calling this
680 /// let s = String::from("hello");
681 /// let ptr = s.as_ptr();
682 /// let len = s.len();
683 /// let capacity = s.capacity();
687 /// let s = String::from_raw_parts(ptr as *mut _, len, capacity);
689 /// assert_eq!(String::from("hello"), s);
693 #[stable(feature = "rust1", since = "1.0.0")]
694 pub unsafe fn from_raw_parts(buf: *mut u8, length: usize, capacity: usize) -> String {
695 String { vec: Vec::from_raw_parts(buf, length, capacity) }
698 /// Converts a vector of bytes to a `String` without checking that the
699 /// string contains valid UTF-8.
701 /// See the safe version, [`from_utf8`], for more details.
703 /// [`from_utf8`]: struct.String.html#method.from_utf8
707 /// This function is unsafe because it does not check that the bytes passed
708 /// to it are valid UTF-8. If this constraint is violated, it may cause
709 /// memory unsafety issues with future users of the `String`, as the rest of
710 /// the standard library assumes that `String`s are valid UTF-8.
717 /// // some bytes, in a vector
718 /// let sparkle_heart = vec![240, 159, 146, 150];
720 /// let sparkle_heart = unsafe {
721 /// String::from_utf8_unchecked(sparkle_heart)
724 /// assert_eq!("💖", sparkle_heart);
727 #[stable(feature = "rust1", since = "1.0.0")]
728 pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String {
729 String { vec: bytes }
732 /// Converts a `String` into a byte vector.
734 /// This consumes the `String`, so we do not need to copy its contents.
741 /// let s = String::from("hello");
742 /// let bytes = s.into_bytes();
744 /// assert_eq!(&[104, 101, 108, 108, 111][..], &bytes[..]);
747 #[stable(feature = "rust1", since = "1.0.0")]
748 pub fn into_bytes(self) -> Vec<u8> {
752 /// Extracts a string slice containing the entire string.
759 /// let s = String::from("foo");
761 /// assert_eq!("foo", s.as_str());
764 #[stable(feature = "string_as_str", since = "1.7.0")]
765 pub fn as_str(&self) -> &str {
769 /// Converts a `String` into a mutable string slice.
776 /// let mut s = String::from("foobar");
777 /// let s_mut_str = s.as_mut_str();
779 /// s_mut_str.make_ascii_uppercase();
781 /// assert_eq!("FOOBAR", s_mut_str);
784 #[stable(feature = "string_as_str", since = "1.7.0")]
785 pub fn as_mut_str(&mut self) -> &mut str {
789 /// Appends a given string slice onto the end of this `String`.
796 /// let mut s = String::from("foo");
798 /// s.push_str("bar");
800 /// assert_eq!("foobar", s);
803 #[stable(feature = "rust1", since = "1.0.0")]
804 pub fn push_str(&mut self, string: &str) {
805 self.vec.extend_from_slice(string.as_bytes())
808 /// Returns this `String`'s capacity, in bytes.
815 /// let s = String::with_capacity(10);
817 /// assert!(s.capacity() >= 10);
820 #[stable(feature = "rust1", since = "1.0.0")]
821 pub fn capacity(&self) -> usize {
825 /// Ensures that this `String`'s capacity is at least `additional` bytes
826 /// larger than its length.
828 /// The capacity may be increased by more than `additional` bytes if it
829 /// chooses, to prevent frequent reallocations.
831 /// If you do not want this "at least" behavior, see the [`reserve_exact`]
836 /// Panics if the new capacity overflows [`usize`].
838 /// [`reserve_exact`]: struct.String.html#method.reserve_exact
839 /// [`usize`]: ../../std/primitive.usize.html
846 /// let mut s = String::new();
850 /// assert!(s.capacity() >= 10);
853 /// This may not actually increase the capacity:
856 /// let mut s = String::with_capacity(10);
860 /// // s now has a length of 2 and a capacity of 10
861 /// assert_eq!(2, s.len());
862 /// assert_eq!(10, s.capacity());
864 /// // Since we already have an extra 8 capacity, calling this...
867 /// // ... doesn't actually increase.
868 /// assert_eq!(10, s.capacity());
871 #[stable(feature = "rust1", since = "1.0.0")]
872 pub fn reserve(&mut self, additional: usize) {
873 self.vec.reserve(additional)
876 /// Ensures that this `String`'s capacity is `additional` bytes
877 /// larger than its length.
879 /// Consider using the [`reserve`] method unless you absolutely know
880 /// better than the allocator.
882 /// [`reserve`]: #method.reserve
886 /// Panics if the new capacity overflows `usize`.
893 /// let mut s = String::new();
895 /// s.reserve_exact(10);
897 /// assert!(s.capacity() >= 10);
900 /// This may not actually increase the capacity:
903 /// let mut s = String::with_capacity(10);
907 /// // s now has a length of 2 and a capacity of 10
908 /// assert_eq!(2, s.len());
909 /// assert_eq!(10, s.capacity());
911 /// // Since we already have an extra 8 capacity, calling this...
912 /// s.reserve_exact(8);
914 /// // ... doesn't actually increase.
915 /// assert_eq!(10, s.capacity());
918 #[stable(feature = "rust1", since = "1.0.0")]
919 pub fn reserve_exact(&mut self, additional: usize) {
920 self.vec.reserve_exact(additional)
923 /// Shrinks the capacity of this `String` to match its length.
930 /// let mut s = String::from("foo");
933 /// assert!(s.capacity() >= 100);
935 /// s.shrink_to_fit();
936 /// assert_eq!(3, s.capacity());
939 #[stable(feature = "rust1", since = "1.0.0")]
940 pub fn shrink_to_fit(&mut self) {
941 self.vec.shrink_to_fit()
944 /// Appends the given [`char`] to the end of this `String`.
946 /// [`char`]: ../../std/primitive.char.html
953 /// let mut s = String::from("abc");
959 /// assert_eq!("abc123", s);
962 #[stable(feature = "rust1", since = "1.0.0")]
963 pub fn push(&mut self, ch: char) {
964 match ch.len_utf8() {
965 1 => self.vec.push(ch as u8),
966 _ => self.vec.extend_from_slice(ch.encode_utf8(&mut [0; 4]).as_bytes()),
970 /// Returns a byte slice of this `String`'s contents.
972 /// The inverse of this method is [`from_utf8`].
974 /// [`from_utf8`]: #method.from_utf8
981 /// let s = String::from("hello");
983 /// assert_eq!(&[104, 101, 108, 108, 111], s.as_bytes());
986 #[stable(feature = "rust1", since = "1.0.0")]
987 pub fn as_bytes(&self) -> &[u8] {
991 /// Shortens this `String` to the specified length.
993 /// If `new_len` is greater than the string's current length, this has no
996 /// Note that this method has no effect on the allocated capacity
1001 /// Panics if `new_len` does not lie on a [`char`] boundary.
1003 /// [`char`]: ../../std/primitive.char.html
1010 /// let mut s = String::from("hello");
1014 /// assert_eq!("he", s);
1017 #[stable(feature = "rust1", since = "1.0.0")]
1018 pub fn truncate(&mut self, new_len: usize) {
1019 if new_len <= self.len() {
1020 assert!(self.is_char_boundary(new_len));
1021 self.vec.truncate(new_len)
1025 /// Removes the last character from the string buffer and returns it.
1027 /// Returns [`None`] if this `String` is empty.
1029 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1036 /// let mut s = String::from("foo");
1038 /// assert_eq!(s.pop(), Some('o'));
1039 /// assert_eq!(s.pop(), Some('o'));
1040 /// assert_eq!(s.pop(), Some('f'));
1042 /// assert_eq!(s.pop(), None);
1045 #[stable(feature = "rust1", since = "1.0.0")]
1046 pub fn pop(&mut self) -> Option<char> {
1047 let ch = self.chars().rev().next()?;
1048 let newlen = self.len() - ch.len_utf8();
1050 self.vec.set_len(newlen);
1055 /// Removes a [`char`] from this `String` at a byte position and returns it.
1057 /// This is an `O(n)` operation, as it requires copying every element in the
1062 /// Panics if `idx` is larger than or equal to the `String`'s length,
1063 /// or if it does not lie on a [`char`] boundary.
1065 /// [`char`]: ../../std/primitive.char.html
1072 /// let mut s = String::from("foo");
1074 /// assert_eq!(s.remove(0), 'f');
1075 /// assert_eq!(s.remove(1), 'o');
1076 /// assert_eq!(s.remove(0), 'o');
1079 #[stable(feature = "rust1", since = "1.0.0")]
1080 pub fn remove(&mut self, idx: usize) -> char {
1081 let ch = match self[idx..].chars().next() {
1083 None => panic!("cannot remove a char from the end of a string"),
1086 let next = idx + ch.len_utf8();
1087 let len = self.len();
1089 ptr::copy(self.vec.as_ptr().offset(next as isize),
1090 self.vec.as_mut_ptr().offset(idx as isize),
1092 self.vec.set_len(len - (next - idx));
1097 /// Retains only the characters specified by the predicate.
1099 /// In other words, remove all characters `c` such that `f(c)` returns `false`.
1100 /// This method operates in place and preserves the order of the retained
1106 /// #![feature(string_retain)]
1108 /// let mut s = String::from("f_o_ob_ar");
1110 /// s.retain(|c| c != '_');
1112 /// assert_eq!(s, "foobar");
1115 #[unstable(feature = "string_retain", issue = "43874")]
1116 pub fn retain<F>(&mut self, mut f: F)
1117 where F: FnMut(char) -> bool
1119 let len = self.len();
1120 let mut del_bytes = 0;
1125 self.slice_unchecked(idx, len).chars().next().unwrap()
1127 let ch_len = ch.len_utf8();
1130 del_bytes += ch_len;
1131 } else if del_bytes > 0 {
1133 ptr::copy(self.vec.as_ptr().offset(idx as isize),
1134 self.vec.as_mut_ptr().offset((idx - del_bytes) as isize),
1139 // Point idx to the next char
1144 unsafe { self.vec.set_len(len - del_bytes); }
1148 /// Inserts a character into this `String` at a byte position.
1150 /// This is an `O(n)` operation as it requires copying every element in the
1155 /// Panics if `idx` is larger than the `String`'s length, or if it does not
1156 /// lie on a [`char`] boundary.
1158 /// [`char`]: ../../std/primitive.char.html
1165 /// let mut s = String::with_capacity(3);
1167 /// s.insert(0, 'f');
1168 /// s.insert(1, 'o');
1169 /// s.insert(2, 'o');
1171 /// assert_eq!("foo", s);
1174 #[stable(feature = "rust1", since = "1.0.0")]
1175 pub fn insert(&mut self, idx: usize, ch: char) {
1176 assert!(self.is_char_boundary(idx));
1177 let mut bits = [0; 4];
1178 let bits = ch.encode_utf8(&mut bits).as_bytes();
1181 self.insert_bytes(idx, bits);
1185 unsafe fn insert_bytes(&mut self, idx: usize, bytes: &[u8]) {
1186 let len = self.len();
1187 let amt = bytes.len();
1188 self.vec.reserve(amt);
1190 ptr::copy(self.vec.as_ptr().offset(idx as isize),
1191 self.vec.as_mut_ptr().offset((idx + amt) as isize),
1193 ptr::copy(bytes.as_ptr(),
1194 self.vec.as_mut_ptr().offset(idx as isize),
1196 self.vec.set_len(len + amt);
1199 /// Inserts a string slice into this `String` at a byte position.
1201 /// This is an `O(n)` operation as it requires copying every element in the
1206 /// Panics if `idx` is larger than the `String`'s length, or if it does not
1207 /// lie on a [`char`] boundary.
1209 /// [`char`]: ../../std/primitive.char.html
1216 /// let mut s = String::from("bar");
1218 /// s.insert_str(0, "foo");
1220 /// assert_eq!("foobar", s);
1223 #[stable(feature = "insert_str", since = "1.16.0")]
1224 pub fn insert_str(&mut self, idx: usize, string: &str) {
1225 assert!(self.is_char_boundary(idx));
1228 self.insert_bytes(idx, string.as_bytes());
1232 /// Returns a mutable reference to the contents of this `String`.
1236 /// This function is unsafe because it does not check that the bytes passed
1237 /// to it are valid UTF-8. If this constraint is violated, it may cause
1238 /// memory unsafety issues with future users of the `String`, as the rest of
1239 /// the standard library assumes that `String`s are valid UTF-8.
1246 /// let mut s = String::from("hello");
1249 /// let vec = s.as_mut_vec();
1250 /// assert_eq!(&[104, 101, 108, 108, 111][..], &vec[..]);
1254 /// assert_eq!(s, "olleh");
1257 #[stable(feature = "rust1", since = "1.0.0")]
1258 pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1262 /// Returns the length of this `String`, in bytes.
1269 /// let a = String::from("foo");
1271 /// assert_eq!(a.len(), 3);
1274 #[stable(feature = "rust1", since = "1.0.0")]
1275 pub fn len(&self) -> usize {
1279 /// Returns `true` if this `String` has a length of zero.
1281 /// Returns `false` otherwise.
1288 /// let mut v = String::new();
1289 /// assert!(v.is_empty());
1292 /// assert!(!v.is_empty());
1295 #[stable(feature = "rust1", since = "1.0.0")]
1296 pub fn is_empty(&self) -> bool {
1300 /// Splits the string into two at the given index.
1302 /// Returns a newly allocated `String`. `self` contains bytes `[0, at)`, and
1303 /// the returned `String` contains bytes `[at, len)`. `at` must be on the
1304 /// boundary of a UTF-8 code point.
1306 /// Note that the capacity of `self` does not change.
1310 /// Panics if `at` is not on a `UTF-8` code point boundary, or if it is beyond the last
1311 /// code point of the string.
1317 /// let mut hello = String::from("Hello, World!");
1318 /// let world = hello.split_off(7);
1319 /// assert_eq!(hello, "Hello, ");
1320 /// assert_eq!(world, "World!");
1324 #[stable(feature = "string_split_off", since = "1.16.0")]
1325 pub fn split_off(&mut self, at: usize) -> String {
1326 assert!(self.is_char_boundary(at));
1327 let other = self.vec.split_off(at);
1328 unsafe { String::from_utf8_unchecked(other) }
1331 /// Truncates this `String`, removing all contents.
1333 /// While this means the `String` will have a length of zero, it does not
1334 /// touch its capacity.
1341 /// let mut s = String::from("foo");
1345 /// assert!(s.is_empty());
1346 /// assert_eq!(0, s.len());
1347 /// assert_eq!(3, s.capacity());
1350 #[stable(feature = "rust1", since = "1.0.0")]
1351 pub fn clear(&mut self) {
1355 /// Creates a draining iterator that removes the specified range in the string
1356 /// and yields the removed chars.
1358 /// Note: The element range is removed even if the iterator is not
1359 /// consumed until the end.
1363 /// Panics if the starting point or end point do not lie on a [`char`]
1364 /// boundary, or if they're out of bounds.
1366 /// [`char`]: ../../std/primitive.char.html
1373 /// let mut s = String::from("α is alpha, β is beta");
1374 /// let beta_offset = s.find('β').unwrap_or(s.len());
1376 /// // Remove the range up until the β from the string
1377 /// let t: String = s.drain(..beta_offset).collect();
1378 /// assert_eq!(t, "α is alpha, ");
1379 /// assert_eq!(s, "β is beta");
1381 /// // A full range clears the string
1383 /// assert_eq!(s, "");
1385 #[stable(feature = "drain", since = "1.6.0")]
1386 pub fn drain<R>(&mut self, range: R) -> Drain
1387 where R: RangeArgument<usize>
1391 // The String version of Drain does not have the memory safety issues
1392 // of the vector version. The data is just plain bytes.
1393 // Because the range removal happens in Drop, if the Drain iterator is leaked,
1394 // the removal will not happen.
1395 let len = self.len();
1396 let start = match range.start() {
1398 Excluded(&n) => n + 1,
1401 let end = match range.end() {
1402 Included(&n) => n + 1,
1407 // Take out two simultaneous borrows. The &mut String won't be accessed
1408 // until iteration is over, in Drop.
1409 let self_ptr = self as *mut _;
1410 // slicing does the appropriate bounds checks
1411 let chars_iter = self[start..end].chars();
1421 /// Creates a splicing iterator that removes the specified range in the string,
1422 /// and replaces it with the given string.
1423 /// The given string doesn't need to be the same length as the range.
1425 /// Note: Unlike [`Vec::splice`], the replacement happens eagerly, and this
1426 /// method does not return the removed chars.
1430 /// Panics if the starting point or end point do not lie on a [`char`]
1431 /// boundary, or if they're out of bounds.
1433 /// [`char`]: ../../std/primitive.char.html
1434 /// [`Vec::splice`]: ../../std/vec/struct.Vec.html#method.splice
1441 /// #![feature(splice)]
1442 /// let mut s = String::from("α is alpha, β is beta");
1443 /// let beta_offset = s.find('β').unwrap_or(s.len());
1445 /// // Replace the range up until the β from the string
1446 /// s.splice(..beta_offset, "Α is capital alpha; ");
1447 /// assert_eq!(s, "Α is capital alpha; β is beta");
1449 #[unstable(feature = "splice", reason = "recently added", issue = "44643")]
1450 pub fn splice<R>(&mut self, range: R, replace_with: &str)
1451 where R: RangeArgument<usize>
1455 // The String version of Splice does not have the memory safety issues
1456 // of the vector version. The data is just plain bytes.
1458 match range.start() {
1459 Included(&n) => assert!(self.is_char_boundary(n)),
1460 Excluded(&n) => assert!(self.is_char_boundary(n + 1)),
1464 Included(&n) => assert!(self.is_char_boundary(n + 1)),
1465 Excluded(&n) => assert!(self.is_char_boundary(n)),
1471 }.splice(range, replace_with.bytes());
1474 /// Converts this `String` into a [`Box`]`<`[`str`]`>`.
1476 /// This will drop any excess capacity.
1478 /// [`Box`]: ../../std/boxed/struct.Box.html
1479 /// [`str`]: ../../std/primitive.str.html
1486 /// let s = String::from("hello");
1488 /// let b = s.into_boxed_str();
1490 #[stable(feature = "box_str", since = "1.4.0")]
1491 pub fn into_boxed_str(self) -> Box<str> {
1492 let slice = self.vec.into_boxed_slice();
1493 unsafe { from_boxed_utf8_unchecked(slice) }
1497 impl FromUtf8Error {
1498 /// Returns a slice of [`u8`]s bytes that were attempted to convert to a `String`.
1505 /// #![feature(from_utf8_error_as_bytes)]
1506 /// // some invalid bytes, in a vector
1507 /// let bytes = vec![0, 159];
1509 /// let value = String::from_utf8(bytes);
1511 /// assert_eq!(&[0, 159], value.unwrap_err().as_bytes());
1513 #[unstable(feature = "from_utf8_error_as_bytes", reason = "recently added", issue = "40895")]
1514 pub fn as_bytes(&self) -> &[u8] {
1518 /// Returns the bytes that were attempted to convert to a `String`.
1520 /// This method is carefully constructed to avoid allocation. It will
1521 /// consume the error, moving out the bytes, so that a copy of the bytes
1522 /// does not need to be made.
1529 /// // some invalid bytes, in a vector
1530 /// let bytes = vec![0, 159];
1532 /// let value = String::from_utf8(bytes);
1534 /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
1536 #[stable(feature = "rust1", since = "1.0.0")]
1537 pub fn into_bytes(self) -> Vec<u8> {
1541 /// Fetch a `Utf8Error` to get more details about the conversion failure.
1543 /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
1544 /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
1545 /// an analogue to `FromUtf8Error`. See its documentation for more details
1548 /// [`Utf8Error`]: ../../std/str/struct.Utf8Error.html
1549 /// [`std::str`]: ../../std/str/index.html
1550 /// [`u8`]: ../../std/primitive.u8.html
1551 /// [`&str`]: ../../std/primitive.str.html
1558 /// // some invalid bytes, in a vector
1559 /// let bytes = vec![0, 159];
1561 /// let error = String::from_utf8(bytes).unwrap_err().utf8_error();
1563 /// // the first byte is invalid here
1564 /// assert_eq!(1, error.valid_up_to());
1566 #[stable(feature = "rust1", since = "1.0.0")]
1567 pub fn utf8_error(&self) -> Utf8Error {
1572 #[stable(feature = "rust1", since = "1.0.0")]
1573 impl fmt::Display for FromUtf8Error {
1574 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1575 fmt::Display::fmt(&self.error, f)
1579 #[stable(feature = "rust1", since = "1.0.0")]
1580 impl fmt::Display for FromUtf16Error {
1581 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1582 fmt::Display::fmt("invalid utf-16: lone surrogate found", f)
1586 #[stable(feature = "rust1", since = "1.0.0")]
1587 impl Clone for String {
1588 fn clone(&self) -> Self {
1589 String { vec: self.vec.clone() }
1592 fn clone_from(&mut self, source: &Self) {
1593 self.vec.clone_from(&source.vec);
1597 #[stable(feature = "rust1", since = "1.0.0")]
1598 impl FromIterator<char> for String {
1599 fn from_iter<I: IntoIterator<Item = char>>(iter: I) -> String {
1600 let mut buf = String::new();
1606 #[stable(feature = "string_from_iter_by_ref", since = "1.17.0")]
1607 impl<'a> FromIterator<&'a char> for String {
1608 fn from_iter<I: IntoIterator<Item = &'a char>>(iter: I) -> String {
1609 let mut buf = String::new();
1615 #[stable(feature = "rust1", since = "1.0.0")]
1616 impl<'a> FromIterator<&'a str> for String {
1617 fn from_iter<I: IntoIterator<Item = &'a str>>(iter: I) -> String {
1618 let mut buf = String::new();
1624 #[stable(feature = "extend_string", since = "1.4.0")]
1625 impl FromIterator<String> for String {
1626 fn from_iter<I: IntoIterator<Item = String>>(iter: I) -> String {
1627 let mut buf = String::new();
1633 #[stable(feature = "herd_cows", since = "1.19.0")]
1634 impl<'a> FromIterator<Cow<'a, str>> for String {
1635 fn from_iter<I: IntoIterator<Item = Cow<'a, str>>>(iter: I) -> String {
1636 let mut buf = String::new();
1642 #[stable(feature = "rust1", since = "1.0.0")]
1643 impl Extend<char> for String {
1644 fn extend<I: IntoIterator<Item = char>>(&mut self, iter: I) {
1645 let iterator = iter.into_iter();
1646 let (lower_bound, _) = iterator.size_hint();
1647 self.reserve(lower_bound);
1648 for ch in iterator {
1654 #[stable(feature = "extend_ref", since = "1.2.0")]
1655 impl<'a> Extend<&'a char> for String {
1656 fn extend<I: IntoIterator<Item = &'a char>>(&mut self, iter: I) {
1657 self.extend(iter.into_iter().cloned());
1661 #[stable(feature = "rust1", since = "1.0.0")]
1662 impl<'a> Extend<&'a str> for String {
1663 fn extend<I: IntoIterator<Item = &'a str>>(&mut self, iter: I) {
1670 #[stable(feature = "extend_string", since = "1.4.0")]
1671 impl Extend<String> for String {
1672 fn extend<I: IntoIterator<Item = String>>(&mut self, iter: I) {
1679 #[stable(feature = "herd_cows", since = "1.19.0")]
1680 impl<'a> Extend<Cow<'a, str>> for String {
1681 fn extend<I: IntoIterator<Item = Cow<'a, str>>>(&mut self, iter: I) {
1688 /// A convenience impl that delegates to the impl for `&str`
1689 #[unstable(feature = "pattern",
1690 reason = "API not fully fleshed out and ready to be stabilized",
1692 impl<'a, 'b> Pattern<'a> for &'b String {
1693 type Searcher = <&'b str as Pattern<'a>>::Searcher;
1695 fn into_searcher(self, haystack: &'a str) -> <&'b str as Pattern<'a>>::Searcher {
1696 self[..].into_searcher(haystack)
1700 fn is_contained_in(self, haystack: &'a str) -> bool {
1701 self[..].is_contained_in(haystack)
1705 fn is_prefix_of(self, haystack: &'a str) -> bool {
1706 self[..].is_prefix_of(haystack)
1710 #[stable(feature = "rust1", since = "1.0.0")]
1711 impl PartialEq for String {
1713 fn eq(&self, other: &String) -> bool {
1714 PartialEq::eq(&self[..], &other[..])
1717 fn ne(&self, other: &String) -> bool {
1718 PartialEq::ne(&self[..], &other[..])
1722 macro_rules! impl_eq {
1723 ($lhs:ty, $rhs: ty) => {
1724 #[stable(feature = "rust1", since = "1.0.0")]
1725 impl<'a, 'b> PartialEq<$rhs> for $lhs {
1727 fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
1729 fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
1732 #[stable(feature = "rust1", since = "1.0.0")]
1733 impl<'a, 'b> PartialEq<$lhs> for $rhs {
1735 fn eq(&self, other: &$lhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
1737 fn ne(&self, other: &$lhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
1743 impl_eq! { String, str }
1744 impl_eq! { String, &'a str }
1745 impl_eq! { Cow<'a, str>, str }
1746 impl_eq! { Cow<'a, str>, &'b str }
1747 impl_eq! { Cow<'a, str>, String }
1749 #[stable(feature = "rust1", since = "1.0.0")]
1750 impl Default for String {
1751 /// Creates an empty `String`.
1753 fn default() -> String {
1758 #[stable(feature = "rust1", since = "1.0.0")]
1759 impl fmt::Display for String {
1761 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1762 fmt::Display::fmt(&**self, f)
1766 #[stable(feature = "rust1", since = "1.0.0")]
1767 impl fmt::Debug for String {
1769 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1770 fmt::Debug::fmt(&**self, f)
1774 #[stable(feature = "rust1", since = "1.0.0")]
1775 impl hash::Hash for String {
1777 fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
1778 (**self).hash(hasher)
1782 /// Implements the `+` operator for concatenating two strings.
1784 /// This consumes the `String` on the left-hand side and re-uses its buffer (growing it if
1785 /// necessary). This is done to avoid allocating a new `String` and copying the entire contents on
1786 /// every operation, which would lead to `O(n^2)` running time when building an `n`-byte string by
1787 /// repeated concatenation.
1789 /// The string on the right-hand side is only borrowed; its contents are copied into the returned
1794 /// Concatenating two `String`s takes the first by value and borrows the second:
1797 /// let a = String::from("hello");
1798 /// let b = String::from(" world");
1800 /// // `a` is moved and can no longer be used here.
1803 /// If you want to keep using the first `String`, you can clone it and append to the clone instead:
1806 /// let a = String::from("hello");
1807 /// let b = String::from(" world");
1808 /// let c = a.clone() + &b;
1809 /// // `a` is still valid here.
1812 /// Concatenating `&str` slices can be done by converting the first to a `String`:
1815 /// let a = "hello";
1816 /// let b = " world";
1817 /// let c = a.to_string() + b;
1819 #[stable(feature = "rust1", since = "1.0.0")]
1820 impl<'a> Add<&'a str> for String {
1821 type Output = String;
1824 fn add(mut self, other: &str) -> String {
1825 self.push_str(other);
1830 /// Implements the `+=` operator for appending to a `String`.
1832 /// This has the same behavior as the [`push_str`] method.
1834 /// [`push_str`]: struct.String.html#method.push_str
1835 #[stable(feature = "stringaddassign", since = "1.12.0")]
1836 impl<'a> AddAssign<&'a str> for String {
1838 fn add_assign(&mut self, other: &str) {
1839 self.push_str(other);
1843 #[stable(feature = "rust1", since = "1.0.0")]
1844 impl ops::Index<ops::Range<usize>> for String {
1848 fn index(&self, index: ops::Range<usize>) -> &str {
1852 #[stable(feature = "rust1", since = "1.0.0")]
1853 impl ops::Index<ops::RangeTo<usize>> for String {
1857 fn index(&self, index: ops::RangeTo<usize>) -> &str {
1861 #[stable(feature = "rust1", since = "1.0.0")]
1862 impl ops::Index<ops::RangeFrom<usize>> for String {
1866 fn index(&self, index: ops::RangeFrom<usize>) -> &str {
1870 #[stable(feature = "rust1", since = "1.0.0")]
1871 impl ops::Index<ops::RangeFull> for String {
1875 fn index(&self, _index: ops::RangeFull) -> &str {
1876 unsafe { str::from_utf8_unchecked(&self.vec) }
1879 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1880 impl ops::Index<ops::RangeInclusive<usize>> for String {
1884 fn index(&self, index: ops::RangeInclusive<usize>) -> &str {
1885 Index::index(&**self, index)
1888 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1889 impl ops::Index<ops::RangeToInclusive<usize>> for String {
1893 fn index(&self, index: ops::RangeToInclusive<usize>) -> &str {
1894 Index::index(&**self, index)
1898 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
1899 impl ops::IndexMut<ops::Range<usize>> for String {
1901 fn index_mut(&mut self, index: ops::Range<usize>) -> &mut str {
1902 &mut self[..][index]
1905 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
1906 impl ops::IndexMut<ops::RangeTo<usize>> for String {
1908 fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut str {
1909 &mut self[..][index]
1912 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
1913 impl ops::IndexMut<ops::RangeFrom<usize>> for String {
1915 fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut str {
1916 &mut self[..][index]
1919 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
1920 impl ops::IndexMut<ops::RangeFull> for String {
1922 fn index_mut(&mut self, _index: ops::RangeFull) -> &mut str {
1923 unsafe { str::from_utf8_unchecked_mut(&mut *self.vec) }
1926 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1927 impl ops::IndexMut<ops::RangeInclusive<usize>> for String {
1929 fn index_mut(&mut self, index: ops::RangeInclusive<usize>) -> &mut str {
1930 IndexMut::index_mut(&mut **self, index)
1933 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1934 impl ops::IndexMut<ops::RangeToInclusive<usize>> for String {
1936 fn index_mut(&mut self, index: ops::RangeToInclusive<usize>) -> &mut str {
1937 IndexMut::index_mut(&mut **self, index)
1941 #[stable(feature = "rust1", since = "1.0.0")]
1942 impl ops::Deref for String {
1946 fn deref(&self) -> &str {
1947 unsafe { str::from_utf8_unchecked(&self.vec) }
1951 #[stable(feature = "derefmut_for_string", since = "1.3.0")]
1952 impl ops::DerefMut for String {
1954 fn deref_mut(&mut self) -> &mut str {
1955 unsafe { str::from_utf8_unchecked_mut(&mut *self.vec) }
1959 /// An error when parsing a `String`.
1961 /// This `enum` is slightly awkward: it will never actually exist. This error is
1962 /// part of the type signature of the implementation of [`FromStr`] on
1963 /// [`String`]. The return type of [`from_str`], requires that an error be
1964 /// defined, but, given that a [`String`] can always be made into a new
1965 /// [`String`] without error, this type will never actually be returned. As
1966 /// such, it is only here to satisfy said signature, and is useless otherwise.
1968 /// [`FromStr`]: ../../std/str/trait.FromStr.html
1969 /// [`String`]: struct.String.html
1970 /// [`from_str`]: ../../std/str/trait.FromStr.html#tymethod.from_str
1971 #[stable(feature = "str_parse_error", since = "1.5.0")]
1973 pub enum ParseError {}
1975 #[stable(feature = "rust1", since = "1.0.0")]
1976 impl FromStr for String {
1977 type Err = ParseError;
1979 fn from_str(s: &str) -> Result<String, ParseError> {
1984 #[stable(feature = "str_parse_error", since = "1.5.0")]
1985 impl Clone for ParseError {
1986 fn clone(&self) -> ParseError {
1991 #[stable(feature = "str_parse_error", since = "1.5.0")]
1992 impl fmt::Debug for ParseError {
1993 fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result {
1998 #[stable(feature = "str_parse_error2", since = "1.8.0")]
1999 impl fmt::Display for ParseError {
2000 fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result {
2005 #[stable(feature = "str_parse_error", since = "1.5.0")]
2006 impl PartialEq for ParseError {
2007 fn eq(&self, _: &ParseError) -> bool {
2012 #[stable(feature = "str_parse_error", since = "1.5.0")]
2013 impl Eq for ParseError {}
2015 /// A trait for converting a value to a `String`.
2017 /// This trait is automatically implemented for any type which implements the
2018 /// [`Display`] trait. As such, `ToString` shouldn't be implemented directly:
2019 /// [`Display`] should be implemented instead, and you get the `ToString`
2020 /// implementation for free.
2022 /// [`Display`]: ../../std/fmt/trait.Display.html
2023 #[stable(feature = "rust1", since = "1.0.0")]
2024 pub trait ToString {
2025 /// Converts the given value to a `String`.
2033 /// let five = String::from("5");
2035 /// assert_eq!(five, i.to_string());
2037 #[rustc_conversion_suggestion]
2038 #[stable(feature = "rust1", since = "1.0.0")]
2039 fn to_string(&self) -> String;
2044 /// In this implementation, the `to_string` method panics
2045 /// if the `Display` implementation returns an error.
2046 /// This indicates an incorrect `Display` implementation
2047 /// since `fmt::Write for String` never returns an error itself.
2048 #[stable(feature = "rust1", since = "1.0.0")]
2049 impl<T: fmt::Display + ?Sized> ToString for T {
2051 default fn to_string(&self) -> String {
2052 use core::fmt::Write;
2053 let mut buf = String::new();
2054 buf.write_fmt(format_args!("{}", self))
2055 .expect("a Display implementation return an error unexpectedly");
2056 buf.shrink_to_fit();
2061 #[stable(feature = "str_to_string_specialization", since = "1.9.0")]
2062 impl ToString for str {
2064 fn to_string(&self) -> String {
2069 #[stable(feature = "cow_str_to_string_specialization", since = "1.17.0")]
2070 impl<'a> ToString for Cow<'a, str> {
2072 fn to_string(&self) -> String {
2077 #[stable(feature = "string_to_string_specialization", since = "1.17.0")]
2078 impl ToString for String {
2080 fn to_string(&self) -> String {
2085 #[stable(feature = "rust1", since = "1.0.0")]
2086 impl AsRef<str> for String {
2088 fn as_ref(&self) -> &str {
2093 #[stable(feature = "rust1", since = "1.0.0")]
2094 impl AsRef<[u8]> for String {
2096 fn as_ref(&self) -> &[u8] {
2101 #[stable(feature = "rust1", since = "1.0.0")]
2102 impl<'a> From<&'a str> for String {
2103 fn from(s: &'a str) -> String {
2108 // note: test pulls in libstd, which causes errors here
2110 #[stable(feature = "string_from_box", since = "1.18.0")]
2111 impl From<Box<str>> for String {
2112 fn from(s: Box<str>) -> String {
2117 #[stable(feature = "box_from_str", since = "1.20.0")]
2118 impl From<String> for Box<str> {
2119 fn from(s: String) -> Box<str> {
2124 #[stable(feature = "string_from_cow_str", since = "1.14.0")]
2125 impl<'a> From<Cow<'a, str>> for String {
2126 fn from(s: Cow<'a, str>) -> String {
2131 #[stable(feature = "rust1", since = "1.0.0")]
2132 impl<'a> From<&'a str> for Cow<'a, str> {
2134 fn from(s: &'a str) -> Cow<'a, str> {
2139 #[stable(feature = "rust1", since = "1.0.0")]
2140 impl<'a> From<String> for Cow<'a, str> {
2142 fn from(s: String) -> Cow<'a, str> {
2147 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2148 impl<'a> FromIterator<char> for Cow<'a, str> {
2149 fn from_iter<I: IntoIterator<Item = char>>(it: I) -> Cow<'a, str> {
2150 Cow::Owned(FromIterator::from_iter(it))
2154 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2155 impl<'a, 'b> FromIterator<&'b str> for Cow<'a, str> {
2156 fn from_iter<I: IntoIterator<Item = &'b str>>(it: I) -> Cow<'a, str> {
2157 Cow::Owned(FromIterator::from_iter(it))
2161 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2162 impl<'a> FromIterator<String> for Cow<'a, str> {
2163 fn from_iter<I: IntoIterator<Item = String>>(it: I) -> Cow<'a, str> {
2164 Cow::Owned(FromIterator::from_iter(it))
2168 #[stable(feature = "from_string_for_vec_u8", since = "1.14.0")]
2169 impl From<String> for Vec<u8> {
2170 fn from(string: String) -> Vec<u8> {
2175 #[stable(feature = "rust1", since = "1.0.0")]
2176 impl fmt::Write for String {
2178 fn write_str(&mut self, s: &str) -> fmt::Result {
2184 fn write_char(&mut self, c: char) -> fmt::Result {
2190 /// A draining iterator for `String`.
2192 /// This struct is created by the [`drain`] method on [`String`]. See its
2193 /// documentation for more.
2195 /// [`drain`]: struct.String.html#method.drain
2196 /// [`String`]: struct.String.html
2197 #[stable(feature = "drain", since = "1.6.0")]
2198 pub struct Drain<'a> {
2199 /// Will be used as &'a mut String in the destructor
2200 string: *mut String,
2201 /// Start of part to remove
2203 /// End of part to remove
2205 /// Current remaining range to remove
2209 #[stable(feature = "collection_debug", since = "1.17.0")]
2210 impl<'a> fmt::Debug for Drain<'a> {
2211 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2212 f.pad("Drain { .. }")
2216 #[stable(feature = "drain", since = "1.6.0")]
2217 unsafe impl<'a> Sync for Drain<'a> {}
2218 #[stable(feature = "drain", since = "1.6.0")]
2219 unsafe impl<'a> Send for Drain<'a> {}
2221 #[stable(feature = "drain", since = "1.6.0")]
2222 impl<'a> Drop for Drain<'a> {
2223 fn drop(&mut self) {
2225 // Use Vec::drain. "Reaffirm" the bounds checks to avoid
2226 // panic code being inserted again.
2227 let self_vec = (*self.string).as_mut_vec();
2228 if self.start <= self.end && self.end <= self_vec.len() {
2229 self_vec.drain(self.start..self.end);
2235 #[stable(feature = "drain", since = "1.6.0")]
2236 impl<'a> Iterator for Drain<'a> {
2240 fn next(&mut self) -> Option<char> {
2244 fn size_hint(&self) -> (usize, Option<usize>) {
2245 self.iter.size_hint()
2249 #[stable(feature = "drain", since = "1.6.0")]
2250 impl<'a> DoubleEndedIterator for Drain<'a> {
2252 fn next_back(&mut self) -> Option<char> {
2253 self.iter.next_back()
2257 #[stable(feature = "fused", since = "1.26.0")]
2258 impl<'a> FusedIterator for Drain<'a> {}