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};
63 use core::ops::{self, Add, AddAssign, Index, IndexMut};
65 use core::str as core_str;
66 use core::str::pattern::Pattern;
67 use std_unicode::char::{decode_utf16, REPLACEMENT_CHARACTER};
69 use borrow::{Cow, ToOwned};
70 use range::RangeArgument;
71 use Bound::{Excluded, Included, Unbounded};
72 use str::{self, FromStr, Utf8Error, Chars};
76 /// A UTF-8 encoded, growable string.
78 /// The `String` type is the most common string type that has ownership over the
79 /// contents of the string. It has a close relationship with its borrowed
80 /// counterpart, the primitive [`str`].
82 /// [`str`]: ../../std/primitive.str.html
86 /// You can create a `String` from a literal string with `String::from`:
89 /// let hello = String::from("Hello, world!");
92 /// You can append a [`char`] to a `String` with the [`push`] method, and
93 /// append a [`&str`] with the [`push_str`] method:
96 /// let mut hello = String::from("Hello, ");
99 /// hello.push_str("orld!");
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`:
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 any
149 /// function which takes a [`&str`] by using an ampersand (`&`):
152 /// fn takes_str(s: &str) { }
154 /// let s = String::from("Hello");
159 /// [`&str`]: ../../std/primitive.str.html
160 /// [`Deref`]: ../../std/ops/trait.Deref.html
162 /// This will create a [`&str`] from the `String` and pass it in. This
163 /// conversion is very inexpensive, and so generally, functions will accept
164 /// [`&str`]s as arguments unless they need a `String` for some specific reason.
169 /// A `String` is made up of three components: a pointer to some bytes, a
170 /// length, and a capacity. The pointer points to an internal buffer `String`
171 /// uses to store its data. The length is the number of bytes currently stored
172 /// in the buffer, and the capacity is the size of the buffer in bytes. As such,
173 /// the length will always be less than or equal to the capacity.
175 /// This buffer is always stored on the heap.
177 /// You can look at these with the [`as_ptr`], [`len`], and [`capacity`]
183 /// let story = String::from("Once upon a time...");
185 /// let ptr = story.as_ptr();
186 /// let len = story.len();
187 /// let capacity = story.capacity();
189 /// // story has nineteen bytes
190 /// assert_eq!(19, len);
192 /// // Now that we have our parts, we throw the story away.
193 /// mem::forget(story);
195 /// // We can re-build a String out of ptr, len, and capacity. This is all
196 /// // unsafe because we are responsible for making sure the components are
198 /// let s = unsafe { String::from_raw_parts(ptr as *mut _, len, capacity) } ;
200 /// assert_eq!(String::from("Once upon a time..."), s);
203 /// [`as_ptr`]: #method.as_ptr
204 /// [`len`]: #method.len
205 /// [`capacity`]: #method.capacity
207 /// If a `String` has enough capacity, adding elements to it will not
208 /// re-allocate. For example, consider this program:
211 /// let mut s = String::new();
213 /// println!("{}", s.capacity());
216 /// s.push_str("hello");
217 /// println!("{}", s.capacity());
221 /// This will output the following:
232 /// At first, we have no memory allocated at all, but as we append to the
233 /// string, it increases its capacity appropriately. If we instead use the
234 /// [`with_capacity`] method to allocate the correct capacity initially:
237 /// let mut s = String::with_capacity(25);
239 /// println!("{}", s.capacity());
242 /// s.push_str("hello");
243 /// println!("{}", s.capacity());
247 /// [`with_capacity`]: #method.with_capacity
249 /// We end up with a different output:
260 /// Here, there's no need to allocate more memory inside the loop.
261 #[derive(PartialOrd, Eq, Ord)]
262 #[stable(feature = "rust1", since = "1.0.0")]
267 /// A possible error value when converting a `String` from a UTF-8 byte vector.
269 /// This type is the error type for the [`from_utf8`] method on [`String`]. It
270 /// is designed in such a way to carefully avoid reallocations: the
271 /// [`into_bytes`] method will give back the byte vector that was used in the
272 /// conversion attempt.
274 /// [`from_utf8`]: struct.String.html#method.from_utf8
275 /// [`String`]: struct.String.html
276 /// [`into_bytes`]: struct.FromUtf8Error.html#method.into_bytes
278 /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
279 /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
280 /// an analogue to `FromUtf8Error`, and you can get one from a `FromUtf8Error`
281 /// through the [`utf8_error`] method.
283 /// [`Utf8Error`]: ../../std/str/struct.Utf8Error.html
284 /// [`std::str`]: ../../std/str/index.html
285 /// [`u8`]: ../../std/primitive.u8.html
286 /// [`&str`]: ../../std/primitive.str.html
287 /// [`utf8_error`]: #method.utf8_error
294 /// // some invalid bytes, in a vector
295 /// let bytes = vec![0, 159];
297 /// let value = String::from_utf8(bytes);
299 /// assert!(value.is_err());
300 /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
302 #[stable(feature = "rust1", since = "1.0.0")]
304 pub struct FromUtf8Error {
309 /// A possible error value when converting a `String` from a UTF-16 byte slice.
311 /// This type is the error type for the [`from_utf16`] method on [`String`].
313 /// [`from_utf16`]: struct.String.html#method.from_utf16
314 /// [`String`]: struct.String.html
321 /// // 𝄞mu<invalid>ic
322 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
323 /// 0xD800, 0x0069, 0x0063];
325 /// assert!(String::from_utf16(v).is_err());
327 #[stable(feature = "rust1", since = "1.0.0")]
329 pub struct FromUtf16Error(());
332 /// Creates a new empty `String`.
334 /// Given that the `String` is empty, this will not allocate any initial
335 /// buffer. While that means that this initial operation is very
336 /// inexpensive, but may cause excessive allocation later, when you add
337 /// data. If you have an idea of how much data the `String` will hold,
338 /// consider the [`with_capacity`] method to prevent excessive
341 /// [`with_capacity`]: #method.with_capacity
348 /// let s = String::new();
351 #[stable(feature = "rust1", since = "1.0.0")]
352 pub fn new() -> String {
353 String { vec: Vec::new() }
356 /// Creates a new empty `String` with a particular capacity.
358 /// `String`s have an internal buffer to hold their data. The capacity is
359 /// the length of that buffer, and can be queried with the [`capacity`]
360 /// method. This method creates an empty `String`, but one with an initial
361 /// buffer that can hold `capacity` bytes. This is useful when you may be
362 /// appending a bunch of data to the `String`, reducing the number of
363 /// reallocations it needs to do.
365 /// [`capacity`]: #method.capacity
367 /// If the given capacity is `0`, no allocation will occur, and this method
368 /// is identical to the [`new`] method.
370 /// [`new`]: #method.new
377 /// let mut s = String::with_capacity(10);
379 /// // The String contains no chars, even though it has capacity for more
380 /// assert_eq!(s.len(), 0);
382 /// // These are all done without reallocating...
383 /// let cap = s.capacity();
388 /// assert_eq!(s.capacity(), cap);
390 /// // ...but this may make the vector reallocate
394 #[stable(feature = "rust1", since = "1.0.0")]
395 pub fn with_capacity(capacity: usize) -> String {
396 String { vec: Vec::with_capacity(capacity) }
399 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
400 // required for this method definition, is not available. Since we don't
401 // require this method for testing purposes, I'll just stub it
402 // NB see the slice::hack module in slice.rs for more information
405 pub fn from_str(_: &str) -> String {
406 panic!("not available with cfg(test)");
409 /// Converts a vector of bytes to a `String`.
411 /// A string slice ([`&str`]) is made of bytes ([`u8`]), and a vector of bytes
412 /// ([`Vec<u8>`]) is made of bytes, so this function converts between the
413 /// two. Not all byte slices are valid `String`s, however: `String`
414 /// requires that it is valid UTF-8. `from_utf8()` checks to ensure that
415 /// the bytes are valid UTF-8, and then does the conversion.
417 /// [`&str`]: ../../std/primitive.str.html
418 /// [`u8`]: ../../std/primitive.u8.html
419 /// [`Vec<u8>`]: ../../std/vec/struct.Vec.html
421 /// If you are sure that the byte slice is valid UTF-8, and you don't want
422 /// to incur the overhead of the validity check, there is an unsafe version
423 /// of this function, [`from_utf8_unchecked`], which has the same behavior
424 /// but skips the check.
426 /// [`from_utf8_unchecked`]: struct.String.html#method.from_utf8_unchecked
428 /// This method will take care to not copy the vector, for efficiency's
431 /// If you need a `&str` instead of a `String`, consider
432 /// [`str::from_utf8`].
434 /// [`str::from_utf8`]: ../../std/str/fn.from_utf8.html
436 /// The inverse of this method is [`as_bytes`].
438 /// [`as_bytes`]: #method.as_bytes
442 /// Returns `Err` if the slice is not UTF-8 with a description as to why the
443 /// provided bytes are not UTF-8. The vector you moved in is also included.
450 /// // some bytes, in a vector
451 /// let sparkle_heart = vec![240, 159, 146, 150];
453 /// // We know these bytes are valid, so we'll use `unwrap()`.
454 /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
456 /// assert_eq!("💖", sparkle_heart);
462 /// // some invalid bytes, in a vector
463 /// let sparkle_heart = vec![0, 159, 146, 150];
465 /// assert!(String::from_utf8(sparkle_heart).is_err());
468 /// See the docs for [`FromUtf8Error`] for more details on what you can do
471 /// [`FromUtf8Error`]: struct.FromUtf8Error.html
473 #[stable(feature = "rust1", since = "1.0.0")]
474 pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error> {
475 match str::from_utf8(&vec) {
476 Ok(..) => Ok(String { vec: vec }),
486 /// Converts a slice of bytes to a string, including invalid characters.
488 /// Strings are made of bytes ([`u8`]), and a slice of bytes
489 /// ([`&[u8]`][byteslice]) is made of bytes, so this function converts
490 /// between the two. Not all byte slices are valid strings, however: strings
491 /// are required to be valid UTF-8. During this conversion,
492 /// `from_utf8_lossy()` will replace any invalid UTF-8 sequences with
493 /// `U+FFFD REPLACEMENT CHARACTER`, which looks like this: �
495 /// [`u8`]: ../../std/primitive.u8.html
496 /// [byteslice]: ../../std/primitive.slice.html
498 /// If you are sure that the byte slice is valid UTF-8, and you don't want
499 /// to incur the overhead of the conversion, there is an unsafe version
500 /// of this function, [`from_utf8_unchecked`], which has the same behavior
501 /// but skips the checks.
503 /// [`from_utf8_unchecked`]: struct.String.html#method.from_utf8_unchecked
505 /// This function returns a [`Cow<'a, str>`]. If our byte slice is invalid
506 /// UTF-8, then we need to insert the replacement characters, which will
507 /// change the size of the string, and hence, require a `String`. But if
508 /// it's already valid UTF-8, we don't need a new allocation. This return
509 /// type allows us to handle both cases.
511 /// [`Cow<'a, str>`]: ../../std/borrow/enum.Cow.html
518 /// // some bytes, in a vector
519 /// let sparkle_heart = vec![240, 159, 146, 150];
521 /// let sparkle_heart = String::from_utf8_lossy(&sparkle_heart);
523 /// assert_eq!("💖", sparkle_heart);
529 /// // some invalid bytes
530 /// let input = b"Hello \xF0\x90\x80World";
531 /// let output = String::from_utf8_lossy(input);
533 /// assert_eq!("Hello �World", output);
535 #[stable(feature = "rust1", since = "1.0.0")]
536 pub fn from_utf8_lossy<'a>(v: &'a [u8]) -> Cow<'a, str> {
538 match str::from_utf8(v) {
539 Ok(s) => return Cow::Borrowed(s),
540 Err(e) => i = e.valid_up_to(),
543 const TAG_CONT_U8: u8 = 128;
544 const REPLACEMENT: &'static [u8] = b"\xEF\xBF\xBD"; // U+FFFD in UTF-8
546 fn unsafe_get(xs: &[u8], i: usize) -> u8 {
547 unsafe { *xs.get_unchecked(i) }
549 fn safe_get(xs: &[u8], i: usize, total: usize) -> u8 {
550 if i >= total { 0 } else { unsafe_get(xs, i) }
553 let mut res = String::with_capacity(total);
556 unsafe { res.as_mut_vec().extend_from_slice(&v[..i]) };
559 // subseqidx is the index of the first byte of the subsequence we're
560 // looking at. It's used to copy a bunch of contiguous good codepoints
561 // at once instead of copying them one by one.
562 let mut subseqidx = i;
566 let byte = unsafe_get(v, i);
569 macro_rules! error { () => ({
572 res.as_mut_vec().extend_from_slice(&v[subseqidx..i_]);
575 res.as_mut_vec().extend_from_slice(REPLACEMENT);
580 // subseqidx handles this
582 let w = core_str::utf8_char_width(byte);
586 if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
593 match (byte, safe_get(v, i, total)) {
594 (0xE0, 0xA0...0xBF) => (),
595 (0xE1...0xEC, 0x80...0xBF) => (),
596 (0xED, 0x80...0x9F) => (),
597 (0xEE...0xEF, 0x80...0xBF) => (),
604 if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
611 match (byte, safe_get(v, i, total)) {
612 (0xF0, 0x90...0xBF) => (),
613 (0xF1...0xF3, 0x80...0xBF) => (),
614 (0xF4, 0x80...0x8F) => (),
621 if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
626 if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
639 if subseqidx < total {
640 unsafe { res.as_mut_vec().extend_from_slice(&v[subseqidx..total]) };
645 /// Decode a UTF-16 encoded vector `v` into a `String`, returning `Err`
646 /// if `v` contains any invalid data.
654 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
655 /// 0x0073, 0x0069, 0x0063];
656 /// assert_eq!(String::from("𝄞music"),
657 /// String::from_utf16(v).unwrap());
659 /// // 𝄞mu<invalid>ic
660 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
661 /// 0xD800, 0x0069, 0x0063];
662 /// assert!(String::from_utf16(v).is_err());
664 #[stable(feature = "rust1", since = "1.0.0")]
665 pub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error> {
666 decode_utf16(v.iter().cloned()).collect::<Result<_, _>>().map_err(|_| FromUtf16Error(()))
669 /// Decode a UTF-16 encoded vector `v` into a string, replacing
670 /// invalid data with the replacement character (U+FFFD).
677 /// // 𝄞mus<invalid>ic<invalid>
678 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
679 /// 0x0073, 0xDD1E, 0x0069, 0x0063,
682 /// assert_eq!(String::from("𝄞mus\u{FFFD}ic\u{FFFD}"),
683 /// String::from_utf16_lossy(v));
686 #[stable(feature = "rust1", since = "1.0.0")]
687 pub fn from_utf16_lossy(v: &[u16]) -> String {
688 decode_utf16(v.iter().cloned()).map(|r| r.unwrap_or(REPLACEMENT_CHARACTER)).collect()
691 /// Creates a new `String` from a length, capacity, and pointer.
695 /// This is highly unsafe, due to the number of invariants that aren't
698 /// * The memory at `ptr` needs to have been previously allocated by the
699 /// same allocator the standard library uses.
700 /// * `length` needs to be less than or equal to `capacity`.
701 /// * `capacity` needs to be the correct value.
703 /// Violating these may cause problems like corrupting the allocator's
704 /// internal datastructures.
706 /// The ownership of `ptr` is effectively transferred to the
707 /// `String` which may then deallocate, reallocate or change the
708 /// contents of memory pointed to by the pointer at will. Ensure
709 /// that nothing else uses the pointer after calling this
720 /// let s = String::from("hello");
721 /// let ptr = s.as_ptr();
722 /// let len = s.len();
723 /// let capacity = s.capacity();
727 /// let s = String::from_raw_parts(ptr as *mut _, len, capacity);
729 /// assert_eq!(String::from("hello"), s);
733 #[stable(feature = "rust1", since = "1.0.0")]
734 pub unsafe fn from_raw_parts(buf: *mut u8, length: usize, capacity: usize) -> String {
735 String { vec: Vec::from_raw_parts(buf, length, capacity) }
738 /// Converts a vector of bytes to a `String` without checking that the
739 /// string contains valid UTF-8.
741 /// See the safe version, [`from_utf8`], for more details.
743 /// [`from_utf8`]: struct.String.html#method.from_utf8
747 /// This function is unsafe because it does not check that the bytes passed
748 /// to it are valid UTF-8. If this constraint is violated, it may cause
749 /// memory unsafety issues with future users of the `String`, as the rest of
750 /// the standard library assumes that `String`s are valid UTF-8.
757 /// // some bytes, in a vector
758 /// let sparkle_heart = vec![240, 159, 146, 150];
760 /// let sparkle_heart = unsafe {
761 /// String::from_utf8_unchecked(sparkle_heart)
764 /// assert_eq!("💖", sparkle_heart);
767 #[stable(feature = "rust1", since = "1.0.0")]
768 pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String {
769 String { vec: bytes }
772 /// Converts a `String` into a byte vector.
774 /// This consumes the `String`, so we do not need to copy its contents.
781 /// let s = String::from("hello");
782 /// let bytes = s.into_bytes();
784 /// assert_eq!(&[104, 101, 108, 108, 111][..], &bytes[..]);
787 #[stable(feature = "rust1", since = "1.0.0")]
788 pub fn into_bytes(self) -> Vec<u8> {
792 /// Extracts a string slice containing the entire string.
794 #[stable(feature = "string_as_str", since = "1.7.0")]
795 pub fn as_str(&self) -> &str {
799 /// Extracts a string slice containing the entire string.
801 #[stable(feature = "string_as_str", since = "1.7.0")]
802 pub fn as_mut_str(&mut self) -> &mut str {
806 /// Appends a given string slice onto the end of this `String`.
813 /// let mut s = String::from("foo");
815 /// s.push_str("bar");
817 /// assert_eq!("foobar", s);
820 #[stable(feature = "rust1", since = "1.0.0")]
821 pub fn push_str(&mut self, string: &str) {
822 self.vec.extend_from_slice(string.as_bytes())
825 /// Returns this `String`'s capacity, in bytes.
832 /// let s = String::with_capacity(10);
834 /// assert!(s.capacity() >= 10);
837 #[stable(feature = "rust1", since = "1.0.0")]
838 pub fn capacity(&self) -> usize {
842 /// Ensures that this `String`'s capacity is at least `additional` bytes
843 /// larger than its length.
845 /// The capacity may be increased by more than `additional` bytes if it
846 /// chooses, to prevent frequent reallocations.
848 /// If you do not want this "at least" behavior, see the [`reserve_exact`]
851 /// [`reserve_exact`]: #method.reserve_exact
855 /// Panics if the new capacity overflows `usize`.
862 /// let mut s = String::new();
866 /// assert!(s.capacity() >= 10);
869 /// This may not actually increase the capacity:
872 /// let mut s = String::with_capacity(10);
876 /// // s now has a length of 2 and a capacity of 10
877 /// assert_eq!(2, s.len());
878 /// assert_eq!(10, s.capacity());
880 /// // Since we already have an extra 8 capacity, calling this...
883 /// // ... doesn't actually increase.
884 /// assert_eq!(10, s.capacity());
887 #[stable(feature = "rust1", since = "1.0.0")]
888 pub fn reserve(&mut self, additional: usize) {
889 self.vec.reserve(additional)
892 /// Ensures that this `String`'s capacity is `additional` bytes
893 /// larger than its length.
895 /// Consider using the [`reserve`] method unless you absolutely know
896 /// better than the allocator.
898 /// [`reserve`]: #method.reserve
902 /// Panics if the new capacity overflows `usize`.
909 /// let mut s = String::new();
911 /// s.reserve_exact(10);
913 /// assert!(s.capacity() >= 10);
916 /// This may not actually increase the capacity:
919 /// let mut s = String::with_capacity(10);
923 /// // s now has a length of 2 and a capacity of 10
924 /// assert_eq!(2, s.len());
925 /// assert_eq!(10, s.capacity());
927 /// // Since we already have an extra 8 capacity, calling this...
928 /// s.reserve_exact(8);
930 /// // ... doesn't actually increase.
931 /// assert_eq!(10, s.capacity());
934 #[stable(feature = "rust1", since = "1.0.0")]
935 pub fn reserve_exact(&mut self, additional: usize) {
936 self.vec.reserve_exact(additional)
939 /// Shrinks the capacity of this `String` to match its length.
946 /// let mut s = String::from("foo");
949 /// assert!(s.capacity() >= 100);
951 /// s.shrink_to_fit();
952 /// assert_eq!(3, s.capacity());
955 #[stable(feature = "rust1", since = "1.0.0")]
956 pub fn shrink_to_fit(&mut self) {
957 self.vec.shrink_to_fit()
960 /// Appends the given `char` to the end of this `String`.
967 /// let mut s = String::from("abc");
973 /// assert_eq!("abc123", s);
976 #[stable(feature = "rust1", since = "1.0.0")]
977 pub fn push(&mut self, ch: char) {
978 match ch.len_utf8() {
979 1 => self.vec.push(ch as u8),
980 _ => self.vec.extend_from_slice(ch.encode_utf8(&mut [0; 4]).as_bytes()),
984 /// Returns a byte slice of this `String`'s contents.
986 /// The inverse of this method is [`from_utf8`].
988 /// [`from_utf8`]: #method.from_utf8
995 /// let s = String::from("hello");
997 /// assert_eq!(&[104, 101, 108, 108, 111], s.as_bytes());
1000 #[stable(feature = "rust1", since = "1.0.0")]
1001 pub fn as_bytes(&self) -> &[u8] {
1005 /// Shortens this `String` to the specified length.
1007 /// If `new_len` is greater than the string's current length, this has no
1010 /// Note that this method has no effect on the allocated capacity
1015 /// Panics if `new_len` does not lie on a [`char`] boundary.
1017 /// [`char`]: ../../std/primitive.char.html
1024 /// let mut s = String::from("hello");
1028 /// assert_eq!("he", s);
1031 #[stable(feature = "rust1", since = "1.0.0")]
1032 pub fn truncate(&mut self, new_len: usize) {
1033 if new_len <= self.len() {
1034 assert!(self.is_char_boundary(new_len));
1035 self.vec.truncate(new_len)
1039 /// Removes the last character from the string buffer and returns it.
1041 /// Returns `None` if this `String` is empty.
1048 /// let mut s = String::from("foo");
1050 /// assert_eq!(s.pop(), Some('o'));
1051 /// assert_eq!(s.pop(), Some('o'));
1052 /// assert_eq!(s.pop(), Some('f'));
1054 /// assert_eq!(s.pop(), None);
1057 #[stable(feature = "rust1", since = "1.0.0")]
1058 pub fn pop(&mut self) -> Option<char> {
1059 let ch = match self.chars().rev().next() {
1061 None => return None,
1063 let newlen = self.len() - ch.len_utf8();
1065 self.vec.set_len(newlen);
1070 /// Removes a `char` from this `String` at a byte position and returns it.
1072 /// This is an `O(n)` operation, as it requires copying every element in the
1077 /// Panics if `idx` is larger than or equal to the `String`'s length,
1078 /// or if it does not lie on a [`char`] boundary.
1080 /// [`char`]: ../../std/primitive.char.html
1087 /// let mut s = String::from("foo");
1089 /// assert_eq!(s.remove(0), 'f');
1090 /// assert_eq!(s.remove(1), 'o');
1091 /// assert_eq!(s.remove(0), 'o');
1094 #[stable(feature = "rust1", since = "1.0.0")]
1095 pub fn remove(&mut self, idx: usize) -> char {
1096 let ch = match self[idx..].chars().next() {
1098 None => panic!("cannot remove a char from the end of a string"),
1101 let next = idx + ch.len_utf8();
1102 let len = self.len();
1104 ptr::copy(self.vec.as_ptr().offset(next as isize),
1105 self.vec.as_mut_ptr().offset(idx as isize),
1107 self.vec.set_len(len - (next - idx));
1112 /// Inserts a character into this `String` at a byte position.
1114 /// This is an `O(n)` operation as it requires copying every element in the
1119 /// Panics if `idx` is larger than the `String`'s length, or if it does not
1120 /// lie on a [`char`] boundary.
1122 /// [`char`]: ../../std/primitive.char.html
1129 /// let mut s = String::with_capacity(3);
1131 /// s.insert(0, 'f');
1132 /// s.insert(1, 'o');
1133 /// s.insert(2, 'o');
1135 /// assert_eq!("foo", s);
1138 #[stable(feature = "rust1", since = "1.0.0")]
1139 pub fn insert(&mut self, idx: usize, ch: char) {
1140 assert!(self.is_char_boundary(idx));
1141 let mut bits = [0; 4];
1142 let bits = ch.encode_utf8(&mut bits).as_bytes();
1145 self.insert_bytes(idx, bits);
1149 unsafe fn insert_bytes(&mut self, idx: usize, bytes: &[u8]) {
1150 let len = self.len();
1151 let amt = bytes.len();
1152 self.vec.reserve(amt);
1154 ptr::copy(self.vec.as_ptr().offset(idx as isize),
1155 self.vec.as_mut_ptr().offset((idx + amt) as isize),
1157 ptr::copy(bytes.as_ptr(),
1158 self.vec.as_mut_ptr().offset(idx as isize),
1160 self.vec.set_len(len + amt);
1163 /// Inserts a string slice into this `String` at a byte position.
1165 /// This is an `O(n)` operation as it requires copying every element in the
1170 /// Panics if `idx` is larger than the `String`'s length, or if it does not
1171 /// lie on a [`char`] boundary.
1173 /// [`char`]: ../../std/primitive.char.html
1180 /// let mut s = String::from("bar");
1182 /// s.insert_str(0, "foo");
1184 /// assert_eq!("foobar", s);
1187 #[stable(feature = "insert_str", since = "1.16.0")]
1188 pub fn insert_str(&mut self, idx: usize, string: &str) {
1189 assert!(self.is_char_boundary(idx));
1192 self.insert_bytes(idx, string.as_bytes());
1196 /// Returns a mutable reference to the contents of this `String`.
1200 /// This function is unsafe because it does not check that the bytes passed
1201 /// to it are valid UTF-8. If this constraint is violated, it may cause
1202 /// memory unsafety issues with future users of the `String`, as the rest of
1203 /// the standard library assumes that `String`s are valid UTF-8.
1210 /// let mut s = String::from("hello");
1213 /// let vec = s.as_mut_vec();
1214 /// assert_eq!(&[104, 101, 108, 108, 111][..], &vec[..]);
1218 /// assert_eq!(s, "olleh");
1221 #[stable(feature = "rust1", since = "1.0.0")]
1222 pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1226 /// Returns the length of this `String`, in bytes.
1233 /// let a = String::from("foo");
1235 /// assert_eq!(a.len(), 3);
1238 #[stable(feature = "rust1", since = "1.0.0")]
1239 pub fn len(&self) -> usize {
1243 /// Returns `true` if this `String` has a length of zero.
1245 /// Returns `false` otherwise.
1252 /// let mut v = String::new();
1253 /// assert!(v.is_empty());
1256 /// assert!(!v.is_empty());
1259 #[stable(feature = "rust1", since = "1.0.0")]
1260 pub fn is_empty(&self) -> bool {
1264 /// Splits the string into two at the given index.
1266 /// Returns a newly allocated `String`. `self` contains bytes `[0, at)`, and
1267 /// the returned `String` contains bytes `[at, len)`. `at` must be on the
1268 /// boundary of a UTF-8 code point.
1270 /// Note that the capacity of `self` does not change.
1274 /// Panics if `at` is not on a `UTF-8` code point boundary, or if it is beyond the last
1275 /// code point of the string.
1281 /// let mut hello = String::from("Hello, World!");
1282 /// let world = hello.split_off(7);
1283 /// assert_eq!(hello, "Hello, ");
1284 /// assert_eq!(world, "World!");
1288 #[stable(feature = "string_split_off", since = "1.16.0")]
1289 pub fn split_off(&mut self, at: usize) -> String {
1290 assert!(self.is_char_boundary(at));
1291 let other = self.vec.split_off(at);
1292 unsafe { String::from_utf8_unchecked(other) }
1295 /// Truncates this `String`, removing all contents.
1297 /// While this means the `String` will have a length of zero, it does not
1298 /// touch its capacity.
1305 /// let mut s = String::from("foo");
1309 /// assert!(s.is_empty());
1310 /// assert_eq!(0, s.len());
1311 /// assert_eq!(3, s.capacity());
1314 #[stable(feature = "rust1", since = "1.0.0")]
1315 pub fn clear(&mut self) {
1319 /// Create a draining iterator that removes the specified range in the string
1320 /// and yields the removed chars.
1322 /// Note: The element range is removed even if the iterator is not
1323 /// consumed until the end.
1327 /// Panics if the starting point or end point do not lie on a [`char`]
1328 /// boundary, or if they're out of bounds.
1330 /// [`char`]: ../../std/primitive.char.html
1337 /// let mut s = String::from("α is alpha, β is beta");
1338 /// let beta_offset = s.find('β').unwrap_or(s.len());
1340 /// // Remove the range up until the β from the string
1341 /// let t: String = s.drain(..beta_offset).collect();
1342 /// assert_eq!(t, "α is alpha, ");
1343 /// assert_eq!(s, "β is beta");
1345 /// // A full range clears the string
1347 /// assert_eq!(s, "");
1349 #[stable(feature = "drain", since = "1.6.0")]
1350 pub fn drain<R>(&mut self, range: R) -> Drain
1351 where R: RangeArgument<usize>
1355 // The String version of Drain does not have the memory safety issues
1356 // of the vector version. The data is just plain bytes.
1357 // Because the range removal happens in Drop, if the Drain iterator is leaked,
1358 // the removal will not happen.
1359 let len = self.len();
1360 let start = match range.start() {
1362 Excluded(&n) => n + 1,
1365 let end = match range.end() {
1366 Included(&n) => n + 1,
1371 // Take out two simultaneous borrows. The &mut String won't be accessed
1372 // until iteration is over, in Drop.
1373 let self_ptr = self as *mut _;
1374 // slicing does the appropriate bounds checks
1375 let chars_iter = self[start..end].chars();
1385 /// Converts this `String` into a `Box<str>`.
1387 /// This will drop any excess capacity.
1394 /// let s = String::from("hello");
1396 /// let b = s.into_boxed_str();
1398 #[stable(feature = "box_str", since = "1.4.0")]
1399 pub fn into_boxed_str(self) -> Box<str> {
1400 let slice = self.vec.into_boxed_slice();
1401 unsafe { mem::transmute::<Box<[u8]>, Box<str>>(slice) }
1405 impl FromUtf8Error {
1406 /// Returns the bytes that were attempted to convert to a `String`.
1408 /// This method is carefully constructed to avoid allocation. It will
1409 /// consume the error, moving out the bytes, so that a copy of the bytes
1410 /// does not need to be made.
1417 /// // some invalid bytes, in a vector
1418 /// let bytes = vec![0, 159];
1420 /// let value = String::from_utf8(bytes);
1422 /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
1424 #[stable(feature = "rust1", since = "1.0.0")]
1425 pub fn into_bytes(self) -> Vec<u8> {
1429 /// Fetch a `Utf8Error` to get more details about the conversion failure.
1431 /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
1432 /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
1433 /// an analogue to `FromUtf8Error`. See its documentation for more details
1436 /// [`Utf8Error`]: ../../std/str/struct.Utf8Error.html
1437 /// [`std::str`]: ../../std/str/index.html
1438 /// [`u8`]: ../../std/primitive.u8.html
1439 /// [`&str`]: ../../std/primitive.str.html
1446 /// // some invalid bytes, in a vector
1447 /// let bytes = vec![0, 159];
1449 /// let error = String::from_utf8(bytes).unwrap_err().utf8_error();
1451 /// // the first byte is invalid here
1452 /// assert_eq!(1, error.valid_up_to());
1454 #[stable(feature = "rust1", since = "1.0.0")]
1455 pub fn utf8_error(&self) -> Utf8Error {
1460 #[stable(feature = "rust1", since = "1.0.0")]
1461 impl fmt::Display for FromUtf8Error {
1462 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1463 fmt::Display::fmt(&self.error, f)
1467 #[stable(feature = "rust1", since = "1.0.0")]
1468 impl fmt::Display for FromUtf16Error {
1469 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1470 fmt::Display::fmt("invalid utf-16: lone surrogate found", f)
1474 #[stable(feature = "rust1", since = "1.0.0")]
1475 impl Clone for String {
1476 fn clone(&self) -> Self {
1477 String { vec: self.vec.clone() }
1480 fn clone_from(&mut self, source: &Self) {
1481 self.vec.clone_from(&source.vec);
1485 #[stable(feature = "rust1", since = "1.0.0")]
1486 impl FromIterator<char> for String {
1487 fn from_iter<I: IntoIterator<Item = char>>(iter: I) -> String {
1488 let mut buf = String::new();
1494 #[stable(feature = "string_from_iter_by_ref", since = "1.17.0")]
1495 impl<'a> FromIterator<&'a char> for String {
1496 fn from_iter<I: IntoIterator<Item = &'a char>>(iter: I) -> String {
1497 let mut buf = String::new();
1503 #[stable(feature = "rust1", since = "1.0.0")]
1504 impl<'a> FromIterator<&'a str> for String {
1505 fn from_iter<I: IntoIterator<Item = &'a str>>(iter: I) -> String {
1506 let mut buf = String::new();
1512 #[stable(feature = "extend_string", since = "1.4.0")]
1513 impl FromIterator<String> for String {
1514 fn from_iter<I: IntoIterator<Item = String>>(iter: I) -> String {
1515 let mut buf = String::new();
1521 #[stable(feature = "rust1", since = "1.0.0")]
1522 impl Extend<char> for String {
1523 fn extend<I: IntoIterator<Item = char>>(&mut self, iter: I) {
1524 let iterator = iter.into_iter();
1525 let (lower_bound, _) = iterator.size_hint();
1526 self.reserve(lower_bound);
1527 for ch in iterator {
1533 #[stable(feature = "extend_ref", since = "1.2.0")]
1534 impl<'a> Extend<&'a char> for String {
1535 fn extend<I: IntoIterator<Item = &'a char>>(&mut self, iter: I) {
1536 self.extend(iter.into_iter().cloned());
1540 #[stable(feature = "rust1", since = "1.0.0")]
1541 impl<'a> Extend<&'a str> for String {
1542 fn extend<I: IntoIterator<Item = &'a str>>(&mut self, iter: I) {
1549 #[stable(feature = "extend_string", since = "1.4.0")]
1550 impl Extend<String> for String {
1551 fn extend<I: IntoIterator<Item = String>>(&mut self, iter: I) {
1558 /// A convenience impl that delegates to the impl for `&str`
1559 #[unstable(feature = "pattern",
1560 reason = "API not fully fleshed out and ready to be stabilized",
1562 impl<'a, 'b> Pattern<'a> for &'b String {
1563 type Searcher = <&'b str as Pattern<'a>>::Searcher;
1565 fn into_searcher(self, haystack: &'a str) -> <&'b str as Pattern<'a>>::Searcher {
1566 self[..].into_searcher(haystack)
1570 fn is_contained_in(self, haystack: &'a str) -> bool {
1571 self[..].is_contained_in(haystack)
1575 fn is_prefix_of(self, haystack: &'a str) -> bool {
1576 self[..].is_prefix_of(haystack)
1580 #[stable(feature = "rust1", since = "1.0.0")]
1581 impl PartialEq for String {
1583 fn eq(&self, other: &String) -> bool {
1584 PartialEq::eq(&self[..], &other[..])
1587 fn ne(&self, other: &String) -> bool {
1588 PartialEq::ne(&self[..], &other[..])
1592 macro_rules! impl_eq {
1593 ($lhs:ty, $rhs: ty) => {
1594 #[stable(feature = "rust1", since = "1.0.0")]
1595 impl<'a, 'b> PartialEq<$rhs> for $lhs {
1597 fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
1599 fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
1602 #[stable(feature = "rust1", since = "1.0.0")]
1603 impl<'a, 'b> PartialEq<$lhs> for $rhs {
1605 fn eq(&self, other: &$lhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
1607 fn ne(&self, other: &$lhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
1613 impl_eq! { String, str }
1614 impl_eq! { String, &'a str }
1615 impl_eq! { Cow<'a, str>, str }
1616 impl_eq! { Cow<'a, str>, &'b str }
1617 impl_eq! { Cow<'a, str>, String }
1619 #[stable(feature = "rust1", since = "1.0.0")]
1620 impl Default for String {
1621 /// Creates an empty `String`.
1623 fn default() -> String {
1628 #[stable(feature = "rust1", since = "1.0.0")]
1629 impl fmt::Display for String {
1631 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1632 fmt::Display::fmt(&**self, f)
1636 #[stable(feature = "rust1", since = "1.0.0")]
1637 impl fmt::Debug for String {
1639 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1640 fmt::Debug::fmt(&**self, f)
1644 #[stable(feature = "rust1", since = "1.0.0")]
1645 impl hash::Hash for String {
1647 fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
1648 (**self).hash(hasher)
1652 /// Implements the `+` operator for concatenating two strings.
1654 /// This consumes the `String` on the left-hand side and re-uses its buffer (growing it if
1655 /// necessary). This is done to avoid allocating a new `String` and copying the entire contents on
1656 /// every operation, which would lead to `O(n^2)` running time when building an `n`-byte string by
1657 /// repeated concatenation.
1659 /// The string on the right-hand side is only borrowed; its contents are copied into the returned
1664 /// Concatenating two `String`s takes the first by value and borrows the second:
1667 /// let a = String::from("hello");
1668 /// let b = String::from(" world");
1670 /// // `a` is moved and can no longer be used here.
1673 /// If you want to keep using the first `String`, you can clone it and append to the clone instead:
1676 /// let a = String::from("hello");
1677 /// let b = String::from(" world");
1678 /// let c = a.clone() + &b;
1679 /// // `a` is still valid here.
1682 /// Concatenating `&str` slices can be done by converting the first to a `String`:
1685 /// let a = "hello";
1686 /// let b = " world";
1687 /// let c = a.to_string() + b;
1689 #[stable(feature = "rust1", since = "1.0.0")]
1690 impl<'a> Add<&'a str> for String {
1691 type Output = String;
1694 fn add(mut self, other: &str) -> String {
1695 self.push_str(other);
1700 /// Implements the `+=` operator for appending to a `String`.
1702 /// This has the same behavior as the [`push_str`] method.
1704 /// [`push_str`]: struct.String.html#method.push_str
1705 #[stable(feature = "stringaddassign", since = "1.12.0")]
1706 impl<'a> AddAssign<&'a str> for String {
1708 fn add_assign(&mut self, other: &str) {
1709 self.push_str(other);
1713 #[stable(feature = "rust1", since = "1.0.0")]
1714 impl ops::Index<ops::Range<usize>> for String {
1718 fn index(&self, index: ops::Range<usize>) -> &str {
1722 #[stable(feature = "rust1", since = "1.0.0")]
1723 impl ops::Index<ops::RangeTo<usize>> for String {
1727 fn index(&self, index: ops::RangeTo<usize>) -> &str {
1731 #[stable(feature = "rust1", since = "1.0.0")]
1732 impl ops::Index<ops::RangeFrom<usize>> for String {
1736 fn index(&self, index: ops::RangeFrom<usize>) -> &str {
1740 #[stable(feature = "rust1", since = "1.0.0")]
1741 impl ops::Index<ops::RangeFull> for String {
1745 fn index(&self, _index: ops::RangeFull) -> &str {
1746 unsafe { str::from_utf8_unchecked(&self.vec) }
1749 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1750 impl ops::Index<ops::RangeInclusive<usize>> for String {
1754 fn index(&self, index: ops::RangeInclusive<usize>) -> &str {
1755 Index::index(&**self, index)
1758 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1759 impl ops::Index<ops::RangeToInclusive<usize>> for String {
1763 fn index(&self, index: ops::RangeToInclusive<usize>) -> &str {
1764 Index::index(&**self, index)
1768 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1769 impl ops::IndexMut<ops::Range<usize>> for String {
1771 fn index_mut(&mut self, index: ops::Range<usize>) -> &mut str {
1772 &mut self[..][index]
1775 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1776 impl ops::IndexMut<ops::RangeTo<usize>> for String {
1778 fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut str {
1779 &mut self[..][index]
1782 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1783 impl ops::IndexMut<ops::RangeFrom<usize>> for String {
1785 fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut str {
1786 &mut self[..][index]
1789 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1790 impl ops::IndexMut<ops::RangeFull> for String {
1792 fn index_mut(&mut self, _index: ops::RangeFull) -> &mut str {
1793 unsafe { mem::transmute(&mut *self.vec) }
1796 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1797 impl ops::IndexMut<ops::RangeInclusive<usize>> for String {
1799 fn index_mut(&mut self, index: ops::RangeInclusive<usize>) -> &mut str {
1800 IndexMut::index_mut(&mut **self, index)
1803 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1804 impl ops::IndexMut<ops::RangeToInclusive<usize>> for String {
1806 fn index_mut(&mut self, index: ops::RangeToInclusive<usize>) -> &mut str {
1807 IndexMut::index_mut(&mut **self, index)
1811 #[stable(feature = "rust1", since = "1.0.0")]
1812 impl ops::Deref for String {
1816 fn deref(&self) -> &str {
1817 unsafe { str::from_utf8_unchecked(&self.vec) }
1821 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1822 impl ops::DerefMut for String {
1824 fn deref_mut(&mut self) -> &mut str {
1825 unsafe { mem::transmute(&mut *self.vec) }
1829 /// An error when parsing a `String`.
1831 /// This `enum` is slightly awkward: it will never actually exist. This error is
1832 /// part of the type signature of the implementation of [`FromStr`] on
1833 /// [`String`]. The return type of [`from_str`], requires that an error be
1834 /// defined, but, given that a [`String`] can always be made into a new
1835 /// [`String`] without error, this type will never actually be returned. As
1836 /// such, it is only here to satisfy said signature, and is useless otherwise.
1838 /// [`FromStr`]: ../../std/str/trait.FromStr.html
1839 /// [`String`]: struct.String.html
1840 /// [`from_str`]: ../../std/str/trait.FromStr.html#tymethod.from_str
1841 #[stable(feature = "str_parse_error", since = "1.5.0")]
1843 pub enum ParseError {}
1845 #[stable(feature = "rust1", since = "1.0.0")]
1846 impl FromStr for String {
1847 type Err = ParseError;
1849 fn from_str(s: &str) -> Result<String, ParseError> {
1854 #[stable(feature = "str_parse_error", since = "1.5.0")]
1855 impl Clone for ParseError {
1856 fn clone(&self) -> ParseError {
1861 #[stable(feature = "str_parse_error", since = "1.5.0")]
1862 impl fmt::Debug for ParseError {
1863 fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result {
1868 #[stable(feature = "str_parse_error2", since = "1.8.0")]
1869 impl fmt::Display for ParseError {
1870 fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result {
1875 #[stable(feature = "str_parse_error", since = "1.5.0")]
1876 impl PartialEq for ParseError {
1877 fn eq(&self, _: &ParseError) -> bool {
1882 #[stable(feature = "str_parse_error", since = "1.5.0")]
1883 impl Eq for ParseError {}
1885 /// A trait for converting a value to a `String`.
1887 /// This trait is automatically implemented for any type which implements the
1888 /// [`Display`] trait. As such, `ToString` shouldn't be implemented directly:
1889 /// [`Display`] should be implemented instead, and you get the `ToString`
1890 /// implementation for free.
1892 /// [`Display`]: ../../std/fmt/trait.Display.html
1893 #[stable(feature = "rust1", since = "1.0.0")]
1894 pub trait ToString {
1895 /// Converts the given value to a `String`.
1903 /// let five = String::from("5");
1905 /// assert_eq!(five, i.to_string());
1907 #[stable(feature = "rust1", since = "1.0.0")]
1908 fn to_string(&self) -> String;
1913 /// In this implementation, the `to_string` method panics
1914 /// if the `Display` implementation returns an error.
1915 /// This indicates an incorrect `Display` implementation
1916 /// since `fmt::Write for String` never returns an error itself.
1917 #[stable(feature = "rust1", since = "1.0.0")]
1918 impl<T: fmt::Display + ?Sized> ToString for T {
1920 default fn to_string(&self) -> String {
1921 use core::fmt::Write;
1922 let mut buf = String::new();
1923 buf.write_fmt(format_args!("{}", self))
1924 .expect("a Display implementation return an error unexpectedly");
1925 buf.shrink_to_fit();
1930 #[stable(feature = "str_to_string_specialization", since = "1.9.0")]
1931 impl ToString for str {
1933 fn to_string(&self) -> String {
1938 #[stable(feature = "cow_str_to_string_specialization", since = "1.17.0")]
1939 impl<'a> ToString for Cow<'a, str> {
1941 fn to_string(&self) -> String {
1946 #[stable(feature = "string_to_string_specialization", since = "1.17.0")]
1947 impl ToString for String {
1949 fn to_string(&self) -> String {
1954 #[stable(feature = "rust1", since = "1.0.0")]
1955 impl AsRef<str> for String {
1957 fn as_ref(&self) -> &str {
1962 #[stable(feature = "rust1", since = "1.0.0")]
1963 impl AsRef<[u8]> for String {
1965 fn as_ref(&self) -> &[u8] {
1970 #[stable(feature = "rust1", since = "1.0.0")]
1971 impl<'a> From<&'a str> for String {
1972 fn from(s: &'a str) -> String {
1977 // note: test pulls in libstd, which causes errors here
1979 #[stable(feature = "string_from_box", since = "1.17.0")]
1980 impl From<Box<str>> for String {
1981 fn from(s: Box<str>) -> String {
1986 #[stable(feature = "box_from_str", since = "1.17.0")]
1987 impl Into<Box<str>> for String {
1988 fn into(self) -> Box<str> {
1989 self.into_boxed_str()
1993 #[stable(feature = "string_from_cow_str", since = "1.14.0")]
1994 impl<'a> From<Cow<'a, str>> for String {
1995 fn from(s: Cow<'a, str>) -> String {
2000 #[stable(feature = "rust1", since = "1.0.0")]
2001 impl<'a> From<&'a str> for Cow<'a, str> {
2003 fn from(s: &'a str) -> Cow<'a, str> {
2008 #[stable(feature = "rust1", since = "1.0.0")]
2009 impl<'a> From<String> for Cow<'a, str> {
2011 fn from(s: String) -> Cow<'a, str> {
2016 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2017 impl<'a> FromIterator<char> for Cow<'a, str> {
2018 fn from_iter<I: IntoIterator<Item = char>>(it: I) -> Cow<'a, str> {
2019 Cow::Owned(FromIterator::from_iter(it))
2023 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2024 impl<'a, 'b> FromIterator<&'b str> for Cow<'a, str> {
2025 fn from_iter<I: IntoIterator<Item = &'b str>>(it: I) -> Cow<'a, str> {
2026 Cow::Owned(FromIterator::from_iter(it))
2030 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2031 impl<'a> FromIterator<String> for Cow<'a, str> {
2032 fn from_iter<I: IntoIterator<Item = String>>(it: I) -> Cow<'a, str> {
2033 Cow::Owned(FromIterator::from_iter(it))
2037 #[stable(feature = "from_string_for_vec_u8", since = "1.14.0")]
2038 impl From<String> for Vec<u8> {
2039 fn from(string: String) -> Vec<u8> {
2044 #[stable(feature = "rust1", since = "1.0.0")]
2045 impl fmt::Write for String {
2047 fn write_str(&mut self, s: &str) -> fmt::Result {
2053 fn write_char(&mut self, c: char) -> fmt::Result {
2059 /// A draining iterator for `String`.
2061 /// This struct is created by the [`drain`] method on [`String`]. See its
2062 /// documentation for more.
2064 /// [`drain`]: struct.String.html#method.drain
2065 /// [`String`]: struct.String.html
2066 #[stable(feature = "drain", since = "1.6.0")]
2067 pub struct Drain<'a> {
2068 /// Will be used as &'a mut String in the destructor
2069 string: *mut String,
2070 /// Start of part to remove
2072 /// End of part to remove
2074 /// Current remaining range to remove
2078 #[stable(feature = "collection_debug", since = "1.17.0")]
2079 impl<'a> fmt::Debug for Drain<'a> {
2080 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2081 f.pad("Drain { .. }")
2085 #[stable(feature = "drain", since = "1.6.0")]
2086 unsafe impl<'a> Sync for Drain<'a> {}
2087 #[stable(feature = "drain", since = "1.6.0")]
2088 unsafe impl<'a> Send for Drain<'a> {}
2090 #[stable(feature = "drain", since = "1.6.0")]
2091 impl<'a> Drop for Drain<'a> {
2092 fn drop(&mut self) {
2094 // Use Vec::drain. "Reaffirm" the bounds checks to avoid
2095 // panic code being inserted again.
2096 let self_vec = (*self.string).as_mut_vec();
2097 if self.start <= self.end && self.end <= self_vec.len() {
2098 self_vec.drain(self.start..self.end);
2104 #[stable(feature = "drain", since = "1.6.0")]
2105 impl<'a> Iterator for Drain<'a> {
2109 fn next(&mut self) -> Option<char> {
2113 fn size_hint(&self) -> (usize, Option<usize>) {
2114 self.iter.size_hint()
2118 #[stable(feature = "drain", since = "1.6.0")]
2119 impl<'a> DoubleEndedIterator for Drain<'a> {
2121 fn next_back(&mut self) -> Option<char> {
2122 self.iter.next_back()
2126 #[unstable(feature = "fused", issue = "35602")]
2127 impl<'a> FusedIterator for Drain<'a> {}