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 alloc::str as alloc_str;
63 use core::iter::{FromIterator, FusedIterator};
64 use core::ops::{self, Add, AddAssign, Index, IndexMut};
66 use core::str as core_str;
67 use core::str::pattern::Pattern;
68 use std_unicode::char::{decode_utf16, REPLACEMENT_CHARACTER};
70 use borrow::{Cow, ToOwned};
71 use range::RangeArgument;
72 use Bound::{Excluded, Included, Unbounded};
73 use str::{self, FromStr, Utf8Error, Chars};
77 /// A UTF-8 encoded, growable string.
79 /// The `String` type is the most common string type that has ownership over the
80 /// contents of the string. It has a close relationship with its borrowed
81 /// counterpart, the primitive [`str`].
83 /// [`str`]: ../../std/primitive.str.html
87 /// You can create a `String` from a literal string with `String::from`:
90 /// let hello = String::from("Hello, world!");
93 /// You can append a [`char`] to a `String` with the [`push`] method, and
94 /// append a [`&str`] with the [`push_str`] method:
97 /// let mut hello = String::from("Hello, ");
100 /// hello.push_str("orld!");
103 /// [`char`]: ../../std/primitive.char.html
104 /// [`push`]: #method.push
105 /// [`push_str`]: #method.push_str
107 /// If you have a vector of UTF-8 bytes, you can create a `String` from it with
108 /// the [`from_utf8`] method:
111 /// // some bytes, in a vector
112 /// let sparkle_heart = vec![240, 159, 146, 150];
114 /// // We know these bytes are valid, so we'll use `unwrap()`.
115 /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
117 /// assert_eq!("💖", sparkle_heart);
120 /// [`from_utf8`]: #method.from_utf8
124 /// `String`s are always valid UTF-8. This has a few implications, the first of
125 /// which is that if you need a non-UTF-8 string, consider [`OsString`]. It is
126 /// similar, but without the UTF-8 constraint. The second implication is that
127 /// you cannot index into a `String`:
132 /// println!("The first letter of s is {}", s[0]); // ERROR!!!
135 /// [`OsString`]: ../../std/ffi/struct.OsString.html
137 /// Indexing is intended to be a constant-time operation, but UTF-8 encoding
138 /// does not allow us to do this. Furthermore, it's not clear what sort of
139 /// thing the index should return: a byte, a codepoint, or a grapheme cluster.
140 /// The [`bytes`] and [`chars`] methods return iterators over the first
141 /// two, respectively.
143 /// [`bytes`]: #method.bytes
144 /// [`chars`]: #method.chars
148 /// `String`s implement [`Deref`]`<Target=str>`, and so inherit all of [`str`]'s
149 /// methods. In addition, this means that you can pass a `String` to any
150 /// function which takes a [`&str`] by using an ampersand (`&`):
153 /// fn takes_str(s: &str) { }
155 /// let s = String::from("Hello");
160 /// [`&str`]: ../../std/primitive.str.html
161 /// [`Deref`]: ../../std/ops/trait.Deref.html
163 /// This will create a [`&str`] from the `String` and pass it in. This
164 /// conversion is very inexpensive, and so generally, functions will accept
165 /// [`&str`]s as arguments unless they need a `String` for some specific reason.
170 /// A `String` is made up of three components: a pointer to some bytes, a
171 /// length, and a capacity. The pointer points to an internal buffer `String`
172 /// uses to store its data. The length is the number of bytes currently stored
173 /// in the buffer, and the capacity is the size of the buffer in bytes. As such,
174 /// the length will always be less than or equal to the capacity.
176 /// This buffer is always stored on the heap.
178 /// You can look at these with the [`as_ptr`], [`len`], and [`capacity`]
184 /// let story = String::from("Once upon a time...");
186 /// let ptr = story.as_ptr();
187 /// let len = story.len();
188 /// let capacity = story.capacity();
190 /// // story has nineteen bytes
191 /// assert_eq!(19, len);
193 /// // Now that we have our parts, we throw the story away.
194 /// mem::forget(story);
196 /// // We can re-build a String out of ptr, len, and capacity. This is all
197 /// // unsafe because we are responsible for making sure the components are
199 /// let s = unsafe { String::from_raw_parts(ptr as *mut _, len, capacity) } ;
201 /// assert_eq!(String::from("Once upon a time..."), s);
204 /// [`as_ptr`]: #method.as_ptr
205 /// [`len`]: #method.len
206 /// [`capacity`]: #method.capacity
208 /// If a `String` has enough capacity, adding elements to it will not
209 /// re-allocate. For example, consider this program:
212 /// let mut s = String::new();
214 /// println!("{}", s.capacity());
217 /// s.push_str("hello");
218 /// println!("{}", s.capacity());
222 /// This will output the following:
233 /// At first, we have no memory allocated at all, but as we append to the
234 /// string, it increases its capacity appropriately. If we instead use the
235 /// [`with_capacity`] method to allocate the correct capacity initially:
238 /// let mut s = String::with_capacity(25);
240 /// println!("{}", s.capacity());
243 /// s.push_str("hello");
244 /// println!("{}", s.capacity());
248 /// [`with_capacity`]: #method.with_capacity
250 /// We end up with a different output:
261 /// Here, there's no need to allocate more memory inside the loop.
262 #[derive(PartialOrd, Eq, Ord)]
263 #[stable(feature = "rust1", since = "1.0.0")]
268 /// A possible error value when converting a `String` from a UTF-8 byte vector.
270 /// This type is the error type for the [`from_utf8`] method on [`String`]. It
271 /// is designed in such a way to carefully avoid reallocations: the
272 /// [`into_bytes`] method will give back the byte vector that was used in the
273 /// conversion attempt.
275 /// [`from_utf8`]: struct.String.html#method.from_utf8
276 /// [`String`]: struct.String.html
277 /// [`into_bytes`]: struct.FromUtf8Error.html#method.into_bytes
279 /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
280 /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
281 /// an analogue to `FromUtf8Error`, and you can get one from a `FromUtf8Error`
282 /// through the [`utf8_error`] method.
284 /// [`Utf8Error`]: ../../std/str/struct.Utf8Error.html
285 /// [`std::str`]: ../../std/str/index.html
286 /// [`u8`]: ../../std/primitive.u8.html
287 /// [`&str`]: ../../std/primitive.str.html
288 /// [`utf8_error`]: #method.utf8_error
295 /// // some invalid bytes, in a vector
296 /// let bytes = vec![0, 159];
298 /// let value = String::from_utf8(bytes);
300 /// assert!(value.is_err());
301 /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
303 #[stable(feature = "rust1", since = "1.0.0")]
305 pub struct FromUtf8Error {
310 /// A possible error value when converting a `String` from a UTF-16 byte slice.
312 /// This type is the error type for the [`from_utf16`] method on [`String`].
314 /// [`from_utf16`]: struct.String.html#method.from_utf16
315 /// [`String`]: struct.String.html
322 /// // 𝄞mu<invalid>ic
323 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
324 /// 0xD800, 0x0069, 0x0063];
326 /// assert!(String::from_utf16(v).is_err());
328 #[stable(feature = "rust1", since = "1.0.0")]
330 pub struct FromUtf16Error(());
333 /// Creates a new empty `String`.
335 /// Given that the `String` is empty, this will not allocate any initial
336 /// buffer. While that means that this initial operation is very
337 /// inexpensive, but may cause excessive allocation later, when you add
338 /// data. If you have an idea of how much data the `String` will hold,
339 /// consider the [`with_capacity`] method to prevent excessive
342 /// [`with_capacity`]: #method.with_capacity
349 /// let s = String::new();
352 #[stable(feature = "rust1", since = "1.0.0")]
353 pub fn new() -> String {
354 String { vec: Vec::new() }
357 /// Creates a new empty `String` with a particular capacity.
359 /// `String`s have an internal buffer to hold their data. The capacity is
360 /// the length of that buffer, and can be queried with the [`capacity`]
361 /// method. This method creates an empty `String`, but one with an initial
362 /// buffer that can hold `capacity` bytes. This is useful when you may be
363 /// appending a bunch of data to the `String`, reducing the number of
364 /// reallocations it needs to do.
366 /// [`capacity`]: #method.capacity
368 /// If the given capacity is `0`, no allocation will occur, and this method
369 /// is identical to the [`new`] method.
371 /// [`new`]: #method.new
378 /// let mut s = String::with_capacity(10);
380 /// // The String contains no chars, even though it has capacity for more
381 /// assert_eq!(s.len(), 0);
383 /// // These are all done without reallocating...
384 /// let cap = s.capacity();
389 /// assert_eq!(s.capacity(), cap);
391 /// // ...but this may make the vector reallocate
395 #[stable(feature = "rust1", since = "1.0.0")]
396 pub fn with_capacity(capacity: usize) -> String {
397 String { vec: Vec::with_capacity(capacity) }
400 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
401 // required for this method definition, is not available. Since we don't
402 // require this method for testing purposes, I'll just stub it
403 // NB see the slice::hack module in slice.rs for more information
406 pub fn from_str(_: &str) -> String {
407 panic!("not available with cfg(test)");
410 /// Converts a vector of bytes to a `String`.
412 /// A string slice ([`&str`]) is made of bytes ([`u8`]), and a vector of bytes
413 /// ([`Vec<u8>`]) is made of bytes, so this function converts between the
414 /// two. Not all byte slices are valid `String`s, however: `String`
415 /// requires that it is valid UTF-8. `from_utf8()` checks to ensure that
416 /// the bytes are valid UTF-8, and then does the conversion.
418 /// [`&str`]: ../../std/primitive.str.html
419 /// [`u8`]: ../../std/primitive.u8.html
420 /// [`Vec<u8>`]: ../../std/vec/struct.Vec.html
422 /// If you are sure that the byte slice is valid UTF-8, and you don't want
423 /// to incur the overhead of the validity check, there is an unsafe version
424 /// of this function, [`from_utf8_unchecked`], which has the same behavior
425 /// but skips the check.
427 /// [`from_utf8_unchecked`]: struct.String.html#method.from_utf8_unchecked
429 /// This method will take care to not copy the vector, for efficiency's
432 /// If you need a `&str` instead of a `String`, consider
433 /// [`str::from_utf8`].
435 /// [`str::from_utf8`]: ../../std/str/fn.from_utf8.html
437 /// The inverse of this method is [`as_bytes`].
439 /// [`as_bytes`]: #method.as_bytes
443 /// Returns `Err` if the slice is not UTF-8 with a description as to why the
444 /// provided bytes are not UTF-8. The vector you moved in is also included.
451 /// // some bytes, in a vector
452 /// let sparkle_heart = vec![240, 159, 146, 150];
454 /// // We know these bytes are valid, so we'll use `unwrap()`.
455 /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
457 /// assert_eq!("💖", sparkle_heart);
463 /// // some invalid bytes, in a vector
464 /// let sparkle_heart = vec![0, 159, 146, 150];
466 /// assert!(String::from_utf8(sparkle_heart).is_err());
469 /// See the docs for [`FromUtf8Error`] for more details on what you can do
472 /// [`FromUtf8Error`]: struct.FromUtf8Error.html
474 #[stable(feature = "rust1", since = "1.0.0")]
475 pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error> {
476 match str::from_utf8(&vec) {
477 Ok(..) => Ok(String { vec: vec }),
487 /// Converts a slice of bytes to a string, including invalid characters.
489 /// Strings are made of bytes ([`u8`]), and a slice of bytes
490 /// ([`&[u8]`][byteslice]) is made of bytes, so this function converts
491 /// between the two. Not all byte slices are valid strings, however: strings
492 /// are required to be valid UTF-8. During this conversion,
493 /// `from_utf8_lossy()` will replace any invalid UTF-8 sequences with
494 /// `U+FFFD REPLACEMENT CHARACTER`, which looks like this: �
496 /// [`u8`]: ../../std/primitive.u8.html
497 /// [byteslice]: ../../std/primitive.slice.html
499 /// If you are sure that the byte slice is valid UTF-8, and you don't want
500 /// to incur the overhead of the conversion, there is an unsafe version
501 /// of this function, [`from_utf8_unchecked`], which has the same behavior
502 /// but skips the checks.
504 /// [`from_utf8_unchecked`]: struct.String.html#method.from_utf8_unchecked
506 /// This function returns a [`Cow<'a, str>`]. If our byte slice is invalid
507 /// UTF-8, then we need to insert the replacement characters, which will
508 /// change the size of the string, and hence, require a `String`. But if
509 /// it's already valid UTF-8, we don't need a new allocation. This return
510 /// type allows us to handle both cases.
512 /// [`Cow<'a, str>`]: ../../std/borrow/enum.Cow.html
519 /// // some bytes, in a vector
520 /// let sparkle_heart = vec![240, 159, 146, 150];
522 /// let sparkle_heart = String::from_utf8_lossy(&sparkle_heart);
524 /// assert_eq!("💖", sparkle_heart);
530 /// // some invalid bytes
531 /// let input = b"Hello \xF0\x90\x80World";
532 /// let output = String::from_utf8_lossy(input);
534 /// assert_eq!("Hello �World", output);
536 #[stable(feature = "rust1", since = "1.0.0")]
537 pub fn from_utf8_lossy<'a>(v: &'a [u8]) -> Cow<'a, str> {
539 match str::from_utf8(v) {
540 Ok(s) => return Cow::Borrowed(s),
541 Err(e) => i = e.valid_up_to(),
544 const TAG_CONT_U8: u8 = 128;
545 const REPLACEMENT: &'static [u8] = b"\xEF\xBF\xBD"; // U+FFFD in UTF-8
547 fn unsafe_get(xs: &[u8], i: usize) -> u8 {
548 unsafe { *xs.get_unchecked(i) }
550 fn safe_get(xs: &[u8], i: usize, total: usize) -> u8 {
551 if i >= total { 0 } else { unsafe_get(xs, i) }
554 let mut res = String::with_capacity(total);
557 unsafe { res.as_mut_vec().extend_from_slice(&v[..i]) };
560 // subseqidx is the index of the first byte of the subsequence we're
561 // looking at. It's used to copy a bunch of contiguous good codepoints
562 // at once instead of copying them one by one.
563 let mut subseqidx = i;
567 let byte = unsafe_get(v, i);
570 macro_rules! error { () => ({
573 res.as_mut_vec().extend_from_slice(&v[subseqidx..i_]);
576 res.as_mut_vec().extend_from_slice(REPLACEMENT);
581 // subseqidx handles this
583 let w = core_str::utf8_char_width(byte);
587 if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
594 match (byte, safe_get(v, i, total)) {
595 (0xE0, 0xA0...0xBF) => (),
596 (0xE1...0xEC, 0x80...0xBF) => (),
597 (0xED, 0x80...0x9F) => (),
598 (0xEE...0xEF, 0x80...0xBF) => (),
605 if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
612 match (byte, safe_get(v, i, total)) {
613 (0xF0, 0x90...0xBF) => (),
614 (0xF1...0xF3, 0x80...0xBF) => (),
615 (0xF4, 0x80...0x8F) => (),
622 if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
627 if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
640 if subseqidx < total {
641 unsafe { res.as_mut_vec().extend_from_slice(&v[subseqidx..total]) };
646 /// Decode a UTF-16 encoded vector `v` into a `String`, returning `Err`
647 /// if `v` contains any invalid data.
655 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
656 /// 0x0073, 0x0069, 0x0063];
657 /// assert_eq!(String::from("𝄞music"),
658 /// String::from_utf16(v).unwrap());
660 /// // 𝄞mu<invalid>ic
661 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
662 /// 0xD800, 0x0069, 0x0063];
663 /// assert!(String::from_utf16(v).is_err());
665 #[stable(feature = "rust1", since = "1.0.0")]
666 pub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error> {
667 decode_utf16(v.iter().cloned()).collect::<Result<_, _>>().map_err(|_| FromUtf16Error(()))
670 /// Decode a UTF-16 encoded vector `v` into a string, replacing
671 /// invalid data with the replacement character (U+FFFD).
678 /// // 𝄞mus<invalid>ic<invalid>
679 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
680 /// 0x0073, 0xDD1E, 0x0069, 0x0063,
683 /// assert_eq!(String::from("𝄞mus\u{FFFD}ic\u{FFFD}"),
684 /// String::from_utf16_lossy(v));
687 #[stable(feature = "rust1", since = "1.0.0")]
688 pub fn from_utf16_lossy(v: &[u16]) -> String {
689 decode_utf16(v.iter().cloned()).map(|r| r.unwrap_or(REPLACEMENT_CHARACTER)).collect()
692 /// Creates a new `String` from a length, capacity, and pointer.
696 /// This is highly unsafe, due to the number of invariants that aren't
699 /// * The memory at `ptr` needs to have been previously allocated by the
700 /// same allocator the standard library uses.
701 /// * `length` needs to be less than or equal to `capacity`.
702 /// * `capacity` needs to be the correct value.
704 /// Violating these may cause problems like corrupting the allocator's
705 /// internal datastructures.
707 /// The ownership of `ptr` is effectively transferred to the
708 /// `String` which may then deallocate, reallocate or change the
709 /// contents of memory pointed to by the pointer at will. Ensure
710 /// that nothing else uses the pointer after calling this
721 /// let s = String::from("hello");
722 /// let ptr = s.as_ptr();
723 /// let len = s.len();
724 /// let capacity = s.capacity();
728 /// let s = String::from_raw_parts(ptr as *mut _, len, capacity);
730 /// assert_eq!(String::from("hello"), s);
734 #[stable(feature = "rust1", since = "1.0.0")]
735 pub unsafe fn from_raw_parts(buf: *mut u8, length: usize, capacity: usize) -> String {
736 String { vec: Vec::from_raw_parts(buf, length, capacity) }
739 /// Converts a vector of bytes to a `String` without checking that the
740 /// string contains valid UTF-8.
742 /// See the safe version, [`from_utf8`], for more details.
744 /// [`from_utf8`]: struct.String.html#method.from_utf8
748 /// This function is unsafe because it does not check that the bytes passed
749 /// to it are valid UTF-8. If this constraint is violated, it may cause
750 /// memory unsafety issues with future users of the `String`, as the rest of
751 /// the standard library assumes that `String`s are valid UTF-8.
758 /// // some bytes, in a vector
759 /// let sparkle_heart = vec![240, 159, 146, 150];
761 /// let sparkle_heart = unsafe {
762 /// String::from_utf8_unchecked(sparkle_heart)
765 /// assert_eq!("💖", sparkle_heart);
768 #[stable(feature = "rust1", since = "1.0.0")]
769 pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String {
770 String { vec: bytes }
773 /// Converts a `String` into a byte vector.
775 /// This consumes the `String`, so we do not need to copy its contents.
782 /// let s = String::from("hello");
783 /// let bytes = s.into_bytes();
785 /// assert_eq!(&[104, 101, 108, 108, 111][..], &bytes[..]);
788 #[stable(feature = "rust1", since = "1.0.0")]
789 pub fn into_bytes(self) -> Vec<u8> {
793 /// Extracts a string slice containing the entire string.
795 #[stable(feature = "string_as_str", since = "1.7.0")]
796 pub fn as_str(&self) -> &str {
800 /// Extracts a string slice containing the entire string.
802 #[stable(feature = "string_as_str", since = "1.7.0")]
803 pub fn as_mut_str(&mut self) -> &mut str {
807 /// Appends a given string slice onto the end of this `String`.
814 /// let mut s = String::from("foo");
816 /// s.push_str("bar");
818 /// assert_eq!("foobar", s);
821 #[stable(feature = "rust1", since = "1.0.0")]
822 pub fn push_str(&mut self, string: &str) {
823 self.vec.extend_from_slice(string.as_bytes())
826 /// Returns this `String`'s capacity, in bytes.
833 /// let s = String::with_capacity(10);
835 /// assert!(s.capacity() >= 10);
838 #[stable(feature = "rust1", since = "1.0.0")]
839 pub fn capacity(&self) -> usize {
843 /// Ensures that this `String`'s capacity is at least `additional` bytes
844 /// larger than its length.
846 /// The capacity may be increased by more than `additional` bytes if it
847 /// chooses, to prevent frequent reallocations.
849 /// If you do not want this "at least" behavior, see the [`reserve_exact`]
852 /// [`reserve_exact`]: #method.reserve_exact
856 /// Panics if the new capacity overflows `usize`.
863 /// let mut s = String::new();
867 /// assert!(s.capacity() >= 10);
870 /// This may not actually increase the capacity:
873 /// let mut s = String::with_capacity(10);
877 /// // s now has a length of 2 and a capacity of 10
878 /// assert_eq!(2, s.len());
879 /// assert_eq!(10, s.capacity());
881 /// // Since we already have an extra 8 capacity, calling this...
884 /// // ... doesn't actually increase.
885 /// assert_eq!(10, s.capacity());
888 #[stable(feature = "rust1", since = "1.0.0")]
889 pub fn reserve(&mut self, additional: usize) {
890 self.vec.reserve(additional)
893 /// Ensures that this `String`'s capacity is `additional` bytes
894 /// larger than its length.
896 /// Consider using the [`reserve`] method unless you absolutely know
897 /// better than the allocator.
899 /// [`reserve`]: #method.reserve
903 /// Panics if the new capacity overflows `usize`.
910 /// let mut s = String::new();
912 /// s.reserve_exact(10);
914 /// assert!(s.capacity() >= 10);
917 /// This may not actually increase the capacity:
920 /// let mut s = String::with_capacity(10);
924 /// // s now has a length of 2 and a capacity of 10
925 /// assert_eq!(2, s.len());
926 /// assert_eq!(10, s.capacity());
928 /// // Since we already have an extra 8 capacity, calling this...
929 /// s.reserve_exact(8);
931 /// // ... doesn't actually increase.
932 /// assert_eq!(10, s.capacity());
935 #[stable(feature = "rust1", since = "1.0.0")]
936 pub fn reserve_exact(&mut self, additional: usize) {
937 self.vec.reserve_exact(additional)
940 /// Shrinks the capacity of this `String` to match its length.
947 /// let mut s = String::from("foo");
950 /// assert!(s.capacity() >= 100);
952 /// s.shrink_to_fit();
953 /// assert_eq!(3, s.capacity());
956 #[stable(feature = "rust1", since = "1.0.0")]
957 pub fn shrink_to_fit(&mut self) {
958 self.vec.shrink_to_fit()
961 /// Appends the given `char` to the end of this `String`.
968 /// let mut s = String::from("abc");
974 /// assert_eq!("abc123", s);
977 #[stable(feature = "rust1", since = "1.0.0")]
978 pub fn push(&mut self, ch: char) {
979 match ch.len_utf8() {
980 1 => self.vec.push(ch as u8),
981 _ => self.vec.extend_from_slice(ch.encode_utf8(&mut [0; 4]).as_bytes()),
985 /// Returns a byte slice of this `String`'s contents.
987 /// The inverse of this method is [`from_utf8`].
989 /// [`from_utf8`]: #method.from_utf8
996 /// let s = String::from("hello");
998 /// assert_eq!(&[104, 101, 108, 108, 111], s.as_bytes());
1001 #[stable(feature = "rust1", since = "1.0.0")]
1002 pub fn as_bytes(&self) -> &[u8] {
1006 /// Shortens this `String` to the specified length.
1008 /// If `new_len` is greater than the string's current length, this has no
1011 /// Note that this method has no effect on the allocated capacity
1016 /// Panics if `new_len` does not lie on a [`char`] boundary.
1018 /// [`char`]: ../../std/primitive.char.html
1025 /// let mut s = String::from("hello");
1029 /// assert_eq!("he", s);
1032 #[stable(feature = "rust1", since = "1.0.0")]
1033 pub fn truncate(&mut self, new_len: usize) {
1034 if new_len <= self.len() {
1035 assert!(self.is_char_boundary(new_len));
1036 self.vec.truncate(new_len)
1040 /// Removes the last character from the string buffer and returns it.
1042 /// Returns `None` if this `String` is empty.
1049 /// let mut s = String::from("foo");
1051 /// assert_eq!(s.pop(), Some('o'));
1052 /// assert_eq!(s.pop(), Some('o'));
1053 /// assert_eq!(s.pop(), Some('f'));
1055 /// assert_eq!(s.pop(), None);
1058 #[stable(feature = "rust1", since = "1.0.0")]
1059 pub fn pop(&mut self) -> Option<char> {
1060 let ch = match self.chars().rev().next() {
1062 None => return None,
1064 let newlen = self.len() - ch.len_utf8();
1066 self.vec.set_len(newlen);
1071 /// Removes a `char` from this `String` at a byte position and returns it.
1073 /// This is an `O(n)` operation, as it requires copying every element in the
1078 /// Panics if `idx` is larger than or equal to the `String`'s length,
1079 /// or if it does not lie on a [`char`] boundary.
1081 /// [`char`]: ../../std/primitive.char.html
1088 /// let mut s = String::from("foo");
1090 /// assert_eq!(s.remove(0), 'f');
1091 /// assert_eq!(s.remove(1), 'o');
1092 /// assert_eq!(s.remove(0), 'o');
1095 #[stable(feature = "rust1", since = "1.0.0")]
1096 pub fn remove(&mut self, idx: usize) -> char {
1097 let ch = match self[idx..].chars().next() {
1099 None => panic!("cannot remove a char from the end of a string"),
1102 let next = idx + ch.len_utf8();
1103 let len = self.len();
1105 ptr::copy(self.vec.as_ptr().offset(next as isize),
1106 self.vec.as_mut_ptr().offset(idx as isize),
1108 self.vec.set_len(len - (next - idx));
1113 /// Inserts a character into this `String` at a byte position.
1115 /// This is an `O(n)` operation as it requires copying every element in the
1120 /// Panics if `idx` is larger than the `String`'s length, or if it does not
1121 /// lie on a [`char`] boundary.
1123 /// [`char`]: ../../std/primitive.char.html
1130 /// let mut s = String::with_capacity(3);
1132 /// s.insert(0, 'f');
1133 /// s.insert(1, 'o');
1134 /// s.insert(2, 'o');
1136 /// assert_eq!("foo", s);
1139 #[stable(feature = "rust1", since = "1.0.0")]
1140 pub fn insert(&mut self, idx: usize, ch: char) {
1141 assert!(self.is_char_boundary(idx));
1142 let mut bits = [0; 4];
1143 let bits = ch.encode_utf8(&mut bits).as_bytes();
1146 self.insert_bytes(idx, bits);
1150 unsafe fn insert_bytes(&mut self, idx: usize, bytes: &[u8]) {
1151 let len = self.len();
1152 let amt = bytes.len();
1153 self.vec.reserve(amt);
1155 ptr::copy(self.vec.as_ptr().offset(idx as isize),
1156 self.vec.as_mut_ptr().offset((idx + amt) as isize),
1158 ptr::copy(bytes.as_ptr(),
1159 self.vec.as_mut_ptr().offset(idx as isize),
1161 self.vec.set_len(len + amt);
1164 /// Inserts a string slice into this `String` at a byte position.
1166 /// This is an `O(n)` operation as it requires copying every element in the
1171 /// Panics if `idx` is larger than the `String`'s length, or if it does not
1172 /// lie on a [`char`] boundary.
1174 /// [`char`]: ../../std/primitive.char.html
1181 /// let mut s = String::from("bar");
1183 /// s.insert_str(0, "foo");
1185 /// assert_eq!("foobar", s);
1188 #[stable(feature = "insert_str", since = "1.16.0")]
1189 pub fn insert_str(&mut self, idx: usize, string: &str) {
1190 assert!(self.is_char_boundary(idx));
1193 self.insert_bytes(idx, string.as_bytes());
1197 /// Returns a mutable reference to the contents of this `String`.
1201 /// This function is unsafe because it does not check that the bytes passed
1202 /// to it are valid UTF-8. If this constraint is violated, it may cause
1203 /// memory unsafety issues with future users of the `String`, as the rest of
1204 /// the standard library assumes that `String`s are valid UTF-8.
1211 /// let mut s = String::from("hello");
1214 /// let vec = s.as_mut_vec();
1215 /// assert_eq!(&[104, 101, 108, 108, 111][..], &vec[..]);
1219 /// assert_eq!(s, "olleh");
1222 #[stable(feature = "rust1", since = "1.0.0")]
1223 pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1227 /// Returns the length of this `String`, in bytes.
1234 /// let a = String::from("foo");
1236 /// assert_eq!(a.len(), 3);
1239 #[stable(feature = "rust1", since = "1.0.0")]
1240 pub fn len(&self) -> usize {
1244 /// Returns `true` if this `String` has a length of zero.
1246 /// Returns `false` otherwise.
1253 /// let mut v = String::new();
1254 /// assert!(v.is_empty());
1257 /// assert!(!v.is_empty());
1260 #[stable(feature = "rust1", since = "1.0.0")]
1261 pub fn is_empty(&self) -> bool {
1265 /// Splits the string into two at the given index.
1267 /// Returns a newly allocated `String`. `self` contains bytes `[0, at)`, and
1268 /// the returned `String` contains bytes `[at, len)`. `at` must be on the
1269 /// boundary of a UTF-8 code point.
1271 /// Note that the capacity of `self` does not change.
1275 /// Panics if `at` is not on a `UTF-8` code point boundary, or if it is beyond the last
1276 /// code point of the string.
1282 /// let mut hello = String::from("Hello, World!");
1283 /// let world = hello.split_off(7);
1284 /// assert_eq!(hello, "Hello, ");
1285 /// assert_eq!(world, "World!");
1289 #[stable(feature = "string_split_off", since = "1.16.0")]
1290 pub fn split_off(&mut self, at: usize) -> String {
1291 assert!(self.is_char_boundary(at));
1292 let other = self.vec.split_off(at);
1293 unsafe { String::from_utf8_unchecked(other) }
1296 /// Truncates this `String`, removing all contents.
1298 /// While this means the `String` will have a length of zero, it does not
1299 /// touch its capacity.
1306 /// let mut s = String::from("foo");
1310 /// assert!(s.is_empty());
1311 /// assert_eq!(0, s.len());
1312 /// assert_eq!(3, s.capacity());
1315 #[stable(feature = "rust1", since = "1.0.0")]
1316 pub fn clear(&mut self) {
1320 /// Create a draining iterator that removes the specified range in the string
1321 /// and yields the removed chars.
1323 /// Note: The element range is removed even if the iterator is not
1324 /// consumed until the end.
1328 /// Panics if the starting point or end point do not lie on a [`char`]
1329 /// boundary, or if they're out of bounds.
1331 /// [`char`]: ../../std/primitive.char.html
1338 /// let mut s = String::from("α is alpha, β is beta");
1339 /// let beta_offset = s.find('β').unwrap_or(s.len());
1341 /// // Remove the range up until the β from the string
1342 /// let t: String = s.drain(..beta_offset).collect();
1343 /// assert_eq!(t, "α is alpha, ");
1344 /// assert_eq!(s, "β is beta");
1346 /// // A full range clears the string
1348 /// assert_eq!(s, "");
1350 #[stable(feature = "drain", since = "1.6.0")]
1351 pub fn drain<R>(&mut self, range: R) -> Drain
1352 where R: RangeArgument<usize>
1356 // The String version of Drain does not have the memory safety issues
1357 // of the vector version. The data is just plain bytes.
1358 // Because the range removal happens in Drop, if the Drain iterator is leaked,
1359 // the removal will not happen.
1360 let len = self.len();
1361 let start = match range.start() {
1363 Excluded(&n) => n + 1,
1366 let end = match range.end() {
1367 Included(&n) => n + 1,
1372 // Take out two simultaneous borrows. The &mut String won't be accessed
1373 // until iteration is over, in Drop.
1374 let self_ptr = self as *mut _;
1375 // slicing does the appropriate bounds checks
1376 let chars_iter = self[start..end].chars();
1386 /// Converts this `String` into a `Box<str>`.
1388 /// This will drop any excess capacity.
1395 /// let s = String::from("hello");
1397 /// let b = s.into_boxed_str();
1399 #[stable(feature = "box_str", since = "1.4.0")]
1400 pub fn into_boxed_str(self) -> Box<str> {
1401 let slice = self.vec.into_boxed_slice();
1402 unsafe { alloc_str::from_boxed_utf8_unchecked(slice) }
1406 impl FromUtf8Error {
1407 /// Returns a slice of [`u8`]s bytes that were attempted to convert to a `String`.
1414 /// #![feature(from_utf8_error_as_bytes)]
1415 /// // some invalid bytes, in a vector
1416 /// let bytes = vec![0, 159];
1418 /// let value = String::from_utf8(bytes);
1420 /// assert_eq!(&[0, 159], value.unwrap_err().as_bytes());
1422 #[unstable(feature = "from_utf8_error_as_bytes", reason = "recently added", issue = "40895")]
1423 pub fn as_bytes(&self) -> &[u8] {
1427 /// Returns the bytes that were attempted to convert to a `String`.
1429 /// This method is carefully constructed to avoid allocation. It will
1430 /// consume the error, moving out the bytes, so that a copy of the bytes
1431 /// does not need to be made.
1438 /// // some invalid bytes, in a vector
1439 /// let bytes = vec![0, 159];
1441 /// let value = String::from_utf8(bytes);
1443 /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
1445 #[stable(feature = "rust1", since = "1.0.0")]
1446 pub fn into_bytes(self) -> Vec<u8> {
1450 /// Fetch a `Utf8Error` to get more details about the conversion failure.
1452 /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
1453 /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
1454 /// an analogue to `FromUtf8Error`. See its documentation for more details
1457 /// [`Utf8Error`]: ../../std/str/struct.Utf8Error.html
1458 /// [`std::str`]: ../../std/str/index.html
1459 /// [`u8`]: ../../std/primitive.u8.html
1460 /// [`&str`]: ../../std/primitive.str.html
1467 /// // some invalid bytes, in a vector
1468 /// let bytes = vec![0, 159];
1470 /// let error = String::from_utf8(bytes).unwrap_err().utf8_error();
1472 /// // the first byte is invalid here
1473 /// assert_eq!(1, error.valid_up_to());
1475 #[stable(feature = "rust1", since = "1.0.0")]
1476 pub fn utf8_error(&self) -> Utf8Error {
1481 #[stable(feature = "rust1", since = "1.0.0")]
1482 impl fmt::Display for FromUtf8Error {
1483 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1484 fmt::Display::fmt(&self.error, f)
1488 #[stable(feature = "rust1", since = "1.0.0")]
1489 impl fmt::Display for FromUtf16Error {
1490 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1491 fmt::Display::fmt("invalid utf-16: lone surrogate found", f)
1495 #[stable(feature = "rust1", since = "1.0.0")]
1496 impl Clone for String {
1497 fn clone(&self) -> Self {
1498 String { vec: self.vec.clone() }
1501 fn clone_from(&mut self, source: &Self) {
1502 self.vec.clone_from(&source.vec);
1506 #[stable(feature = "rust1", since = "1.0.0")]
1507 impl FromIterator<char> for String {
1508 fn from_iter<I: IntoIterator<Item = char>>(iter: I) -> String {
1509 let mut buf = String::new();
1515 #[stable(feature = "string_from_iter_by_ref", since = "1.17.0")]
1516 impl<'a> FromIterator<&'a char> for String {
1517 fn from_iter<I: IntoIterator<Item = &'a char>>(iter: I) -> String {
1518 let mut buf = String::new();
1524 #[stable(feature = "rust1", since = "1.0.0")]
1525 impl<'a> FromIterator<&'a str> for String {
1526 fn from_iter<I: IntoIterator<Item = &'a str>>(iter: I) -> String {
1527 let mut buf = String::new();
1533 #[stable(feature = "extend_string", since = "1.4.0")]
1534 impl FromIterator<String> for String {
1535 fn from_iter<I: IntoIterator<Item = String>>(iter: I) -> String {
1536 let mut buf = String::new();
1542 #[stable(feature = "rust1", since = "1.0.0")]
1543 impl Extend<char> for String {
1544 fn extend<I: IntoIterator<Item = char>>(&mut self, iter: I) {
1545 let iterator = iter.into_iter();
1546 let (lower_bound, _) = iterator.size_hint();
1547 self.reserve(lower_bound);
1548 for ch in iterator {
1554 #[stable(feature = "extend_ref", since = "1.2.0")]
1555 impl<'a> Extend<&'a char> for String {
1556 fn extend<I: IntoIterator<Item = &'a char>>(&mut self, iter: I) {
1557 self.extend(iter.into_iter().cloned());
1561 #[stable(feature = "rust1", since = "1.0.0")]
1562 impl<'a> Extend<&'a str> for String {
1563 fn extend<I: IntoIterator<Item = &'a str>>(&mut self, iter: I) {
1570 #[stable(feature = "extend_string", since = "1.4.0")]
1571 impl Extend<String> for String {
1572 fn extend<I: IntoIterator<Item = String>>(&mut self, iter: I) {
1579 /// A convenience impl that delegates to the impl for `&str`
1580 #[unstable(feature = "pattern",
1581 reason = "API not fully fleshed out and ready to be stabilized",
1583 impl<'a, 'b> Pattern<'a> for &'b String {
1584 type Searcher = <&'b str as Pattern<'a>>::Searcher;
1586 fn into_searcher(self, haystack: &'a str) -> <&'b str as Pattern<'a>>::Searcher {
1587 self[..].into_searcher(haystack)
1591 fn is_contained_in(self, haystack: &'a str) -> bool {
1592 self[..].is_contained_in(haystack)
1596 fn is_prefix_of(self, haystack: &'a str) -> bool {
1597 self[..].is_prefix_of(haystack)
1601 #[stable(feature = "rust1", since = "1.0.0")]
1602 impl PartialEq for String {
1604 fn eq(&self, other: &String) -> bool {
1605 PartialEq::eq(&self[..], &other[..])
1608 fn ne(&self, other: &String) -> bool {
1609 PartialEq::ne(&self[..], &other[..])
1613 macro_rules! impl_eq {
1614 ($lhs:ty, $rhs: ty) => {
1615 #[stable(feature = "rust1", since = "1.0.0")]
1616 impl<'a, 'b> PartialEq<$rhs> for $lhs {
1618 fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
1620 fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
1623 #[stable(feature = "rust1", since = "1.0.0")]
1624 impl<'a, 'b> PartialEq<$lhs> for $rhs {
1626 fn eq(&self, other: &$lhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
1628 fn ne(&self, other: &$lhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
1634 impl_eq! { String, str }
1635 impl_eq! { String, &'a str }
1636 impl_eq! { Cow<'a, str>, str }
1637 impl_eq! { Cow<'a, str>, &'b str }
1638 impl_eq! { Cow<'a, str>, String }
1640 #[stable(feature = "rust1", since = "1.0.0")]
1641 impl Default for String {
1642 /// Creates an empty `String`.
1644 fn default() -> String {
1649 #[stable(feature = "rust1", since = "1.0.0")]
1650 impl fmt::Display for String {
1652 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1653 fmt::Display::fmt(&**self, f)
1657 #[stable(feature = "rust1", since = "1.0.0")]
1658 impl fmt::Debug for String {
1660 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1661 fmt::Debug::fmt(&**self, f)
1665 #[stable(feature = "rust1", since = "1.0.0")]
1666 impl hash::Hash for String {
1668 fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
1669 (**self).hash(hasher)
1673 /// Implements the `+` operator for concatenating two strings.
1675 /// This consumes the `String` on the left-hand side and re-uses its buffer (growing it if
1676 /// necessary). This is done to avoid allocating a new `String` and copying the entire contents on
1677 /// every operation, which would lead to `O(n^2)` running time when building an `n`-byte string by
1678 /// repeated concatenation.
1680 /// The string on the right-hand side is only borrowed; its contents are copied into the returned
1685 /// Concatenating two `String`s takes the first by value and borrows the second:
1688 /// let a = String::from("hello");
1689 /// let b = String::from(" world");
1691 /// // `a` is moved and can no longer be used here.
1694 /// If you want to keep using the first `String`, you can clone it and append to the clone instead:
1697 /// let a = String::from("hello");
1698 /// let b = String::from(" world");
1699 /// let c = a.clone() + &b;
1700 /// // `a` is still valid here.
1703 /// Concatenating `&str` slices can be done by converting the first to a `String`:
1706 /// let a = "hello";
1707 /// let b = " world";
1708 /// let c = a.to_string() + b;
1710 #[stable(feature = "rust1", since = "1.0.0")]
1711 impl<'a> Add<&'a str> for String {
1712 type Output = String;
1715 fn add(mut self, other: &str) -> String {
1716 self.push_str(other);
1721 /// Implements the `+=` operator for appending to a `String`.
1723 /// This has the same behavior as the [`push_str`] method.
1725 /// [`push_str`]: struct.String.html#method.push_str
1726 #[stable(feature = "stringaddassign", since = "1.12.0")]
1727 impl<'a> AddAssign<&'a str> for String {
1729 fn add_assign(&mut self, other: &str) {
1730 self.push_str(other);
1734 #[stable(feature = "rust1", since = "1.0.0")]
1735 impl ops::Index<ops::Range<usize>> for String {
1739 fn index(&self, index: ops::Range<usize>) -> &str {
1743 #[stable(feature = "rust1", since = "1.0.0")]
1744 impl ops::Index<ops::RangeTo<usize>> for String {
1748 fn index(&self, index: ops::RangeTo<usize>) -> &str {
1752 #[stable(feature = "rust1", since = "1.0.0")]
1753 impl ops::Index<ops::RangeFrom<usize>> for String {
1757 fn index(&self, index: ops::RangeFrom<usize>) -> &str {
1761 #[stable(feature = "rust1", since = "1.0.0")]
1762 impl ops::Index<ops::RangeFull> for String {
1766 fn index(&self, _index: ops::RangeFull) -> &str {
1767 unsafe { str::from_utf8_unchecked(&self.vec) }
1770 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1771 impl ops::Index<ops::RangeInclusive<usize>> for String {
1775 fn index(&self, index: ops::RangeInclusive<usize>) -> &str {
1776 Index::index(&**self, index)
1779 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1780 impl ops::Index<ops::RangeToInclusive<usize>> for String {
1784 fn index(&self, index: ops::RangeToInclusive<usize>) -> &str {
1785 Index::index(&**self, index)
1789 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1790 impl ops::IndexMut<ops::Range<usize>> for String {
1792 fn index_mut(&mut self, index: ops::Range<usize>) -> &mut str {
1793 &mut self[..][index]
1796 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1797 impl ops::IndexMut<ops::RangeTo<usize>> for String {
1799 fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut str {
1800 &mut self[..][index]
1803 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1804 impl ops::IndexMut<ops::RangeFrom<usize>> for String {
1806 fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut str {
1807 &mut self[..][index]
1810 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1811 impl ops::IndexMut<ops::RangeFull> for String {
1813 fn index_mut(&mut self, _index: ops::RangeFull) -> &mut str {
1814 unsafe { str::from_utf8_unchecked_mut(&mut *self.vec) }
1817 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1818 impl ops::IndexMut<ops::RangeInclusive<usize>> for String {
1820 fn index_mut(&mut self, index: ops::RangeInclusive<usize>) -> &mut str {
1821 IndexMut::index_mut(&mut **self, index)
1824 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1825 impl ops::IndexMut<ops::RangeToInclusive<usize>> for String {
1827 fn index_mut(&mut self, index: ops::RangeToInclusive<usize>) -> &mut str {
1828 IndexMut::index_mut(&mut **self, index)
1832 #[stable(feature = "rust1", since = "1.0.0")]
1833 impl ops::Deref for String {
1837 fn deref(&self) -> &str {
1838 unsafe { str::from_utf8_unchecked(&self.vec) }
1842 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1843 impl ops::DerefMut for String {
1845 fn deref_mut(&mut self) -> &mut str {
1846 unsafe { str::from_utf8_unchecked_mut(&mut *self.vec) }
1850 /// An error when parsing a `String`.
1852 /// This `enum` is slightly awkward: it will never actually exist. This error is
1853 /// part of the type signature of the implementation of [`FromStr`] on
1854 /// [`String`]. The return type of [`from_str`], requires that an error be
1855 /// defined, but, given that a [`String`] can always be made into a new
1856 /// [`String`] without error, this type will never actually be returned. As
1857 /// such, it is only here to satisfy said signature, and is useless otherwise.
1859 /// [`FromStr`]: ../../std/str/trait.FromStr.html
1860 /// [`String`]: struct.String.html
1861 /// [`from_str`]: ../../std/str/trait.FromStr.html#tymethod.from_str
1862 #[stable(feature = "str_parse_error", since = "1.5.0")]
1864 pub enum ParseError {}
1866 #[stable(feature = "rust1", since = "1.0.0")]
1867 impl FromStr for String {
1868 type Err = ParseError;
1870 fn from_str(s: &str) -> Result<String, ParseError> {
1875 #[stable(feature = "str_parse_error", since = "1.5.0")]
1876 impl Clone for ParseError {
1877 fn clone(&self) -> ParseError {
1882 #[stable(feature = "str_parse_error", since = "1.5.0")]
1883 impl fmt::Debug for ParseError {
1884 fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result {
1889 #[stable(feature = "str_parse_error2", since = "1.8.0")]
1890 impl fmt::Display for ParseError {
1891 fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result {
1896 #[stable(feature = "str_parse_error", since = "1.5.0")]
1897 impl PartialEq for ParseError {
1898 fn eq(&self, _: &ParseError) -> bool {
1903 #[stable(feature = "str_parse_error", since = "1.5.0")]
1904 impl Eq for ParseError {}
1906 /// A trait for converting a value to a `String`.
1908 /// This trait is automatically implemented for any type which implements the
1909 /// [`Display`] trait. As such, `ToString` shouldn't be implemented directly:
1910 /// [`Display`] should be implemented instead, and you get the `ToString`
1911 /// implementation for free.
1913 /// [`Display`]: ../../std/fmt/trait.Display.html
1914 #[stable(feature = "rust1", since = "1.0.0")]
1915 pub trait ToString {
1916 /// Converts the given value to a `String`.
1924 /// let five = String::from("5");
1926 /// assert_eq!(five, i.to_string());
1928 #[stable(feature = "rust1", since = "1.0.0")]
1929 fn to_string(&self) -> String;
1934 /// In this implementation, the `to_string` method panics
1935 /// if the `Display` implementation returns an error.
1936 /// This indicates an incorrect `Display` implementation
1937 /// since `fmt::Write for String` never returns an error itself.
1938 #[stable(feature = "rust1", since = "1.0.0")]
1939 impl<T: fmt::Display + ?Sized> ToString for T {
1941 default fn to_string(&self) -> String {
1942 use core::fmt::Write;
1943 let mut buf = String::new();
1944 buf.write_fmt(format_args!("{}", self))
1945 .expect("a Display implementation return an error unexpectedly");
1946 buf.shrink_to_fit();
1951 #[stable(feature = "str_to_string_specialization", since = "1.9.0")]
1952 impl ToString for str {
1954 fn to_string(&self) -> String {
1959 #[stable(feature = "cow_str_to_string_specialization", since = "1.17.0")]
1960 impl<'a> ToString for Cow<'a, str> {
1962 fn to_string(&self) -> String {
1967 #[stable(feature = "string_to_string_specialization", since = "1.17.0")]
1968 impl ToString for String {
1970 fn to_string(&self) -> String {
1975 #[stable(feature = "rust1", since = "1.0.0")]
1976 impl AsRef<str> for String {
1978 fn as_ref(&self) -> &str {
1983 #[stable(feature = "rust1", since = "1.0.0")]
1984 impl AsRef<[u8]> for String {
1986 fn as_ref(&self) -> &[u8] {
1991 #[stable(feature = "rust1", since = "1.0.0")]
1992 impl<'a> From<&'a str> for String {
1993 fn from(s: &'a str) -> String {
1998 // note: test pulls in libstd, which causes errors here
2000 #[stable(feature = "string_from_box", since = "1.17.0")]
2001 impl From<Box<str>> for String {
2002 fn from(s: Box<str>) -> String {
2007 #[stable(feature = "box_from_str", since = "1.17.0")]
2008 impl Into<Box<str>> for String {
2009 fn into(self) -> Box<str> {
2010 self.into_boxed_str()
2014 #[stable(feature = "string_from_cow_str", since = "1.14.0")]
2015 impl<'a> From<Cow<'a, str>> for String {
2016 fn from(s: Cow<'a, str>) -> String {
2021 #[stable(feature = "rust1", since = "1.0.0")]
2022 impl<'a> From<&'a str> for Cow<'a, str> {
2024 fn from(s: &'a str) -> Cow<'a, str> {
2029 #[stable(feature = "rust1", since = "1.0.0")]
2030 impl<'a> From<String> for Cow<'a, str> {
2032 fn from(s: String) -> Cow<'a, str> {
2037 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2038 impl<'a> FromIterator<char> for Cow<'a, str> {
2039 fn from_iter<I: IntoIterator<Item = char>>(it: I) -> Cow<'a, str> {
2040 Cow::Owned(FromIterator::from_iter(it))
2044 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2045 impl<'a, 'b> FromIterator<&'b str> for Cow<'a, str> {
2046 fn from_iter<I: IntoIterator<Item = &'b str>>(it: I) -> Cow<'a, str> {
2047 Cow::Owned(FromIterator::from_iter(it))
2051 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2052 impl<'a> FromIterator<String> for Cow<'a, str> {
2053 fn from_iter<I: IntoIterator<Item = String>>(it: I) -> Cow<'a, str> {
2054 Cow::Owned(FromIterator::from_iter(it))
2058 #[stable(feature = "from_string_for_vec_u8", since = "1.14.0")]
2059 impl From<String> for Vec<u8> {
2060 fn from(string: String) -> Vec<u8> {
2065 #[stable(feature = "rust1", since = "1.0.0")]
2066 impl fmt::Write for String {
2068 fn write_str(&mut self, s: &str) -> fmt::Result {
2074 fn write_char(&mut self, c: char) -> fmt::Result {
2080 /// A draining iterator for `String`.
2082 /// This struct is created by the [`drain`] method on [`String`]. See its
2083 /// documentation for more.
2085 /// [`drain`]: struct.String.html#method.drain
2086 /// [`String`]: struct.String.html
2087 #[stable(feature = "drain", since = "1.6.0")]
2088 pub struct Drain<'a> {
2089 /// Will be used as &'a mut String in the destructor
2090 string: *mut String,
2091 /// Start of part to remove
2093 /// End of part to remove
2095 /// Current remaining range to remove
2099 #[stable(feature = "collection_debug", since = "1.17.0")]
2100 impl<'a> fmt::Debug for Drain<'a> {
2101 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2102 f.pad("Drain { .. }")
2106 #[stable(feature = "drain", since = "1.6.0")]
2107 unsafe impl<'a> Sync for Drain<'a> {}
2108 #[stable(feature = "drain", since = "1.6.0")]
2109 unsafe impl<'a> Send for Drain<'a> {}
2111 #[stable(feature = "drain", since = "1.6.0")]
2112 impl<'a> Drop for Drain<'a> {
2113 fn drop(&mut self) {
2115 // Use Vec::drain. "Reaffirm" the bounds checks to avoid
2116 // panic code being inserted again.
2117 let self_vec = (*self.string).as_mut_vec();
2118 if self.start <= self.end && self.end <= self_vec.len() {
2119 self_vec.drain(self.start..self.end);
2125 #[stable(feature = "drain", since = "1.6.0")]
2126 impl<'a> Iterator for Drain<'a> {
2130 fn next(&mut self) -> Option<char> {
2134 fn size_hint(&self) -> (usize, Option<usize>) {
2135 self.iter.size_hint()
2139 #[stable(feature = "drain", since = "1.6.0")]
2140 impl<'a> DoubleEndedIterator for Drain<'a> {
2142 fn next_back(&mut self) -> Option<char> {
2143 self.iter.next_back()
2147 #[unstable(feature = "fused", issue = "35602")]
2148 impl<'a> FusedIterator for Drain<'a> {}