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 //! [`String`]: struct.String.html
18 //! [`ToString`]: trait.ToString.html
22 //! There are multiple ways to create a new `String` from a string literal:
25 //! let s = "Hello".to_string();
27 //! let s = String::from("world");
28 //! let s: String = "also this".into();
31 //! You can create a new `String` from an existing one by concatenating with
35 //! let s = "Hello".to_string();
37 //! let message = s + " world!";
40 //! If you have a vector of valid UTF-8 bytes, you can make a `String` out of
41 //! it. You can do the reverse too.
44 //! let sparkle_heart = vec![240, 159, 146, 150];
46 //! // We know these bytes are valid, so we'll use `unwrap()`.
47 //! let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
49 //! assert_eq!("💖", sparkle_heart);
51 //! let bytes = sparkle_heart.into_bytes();
53 //! assert_eq!(bytes, [240, 159, 146, 150]);
56 #![stable(feature = "rust1", since = "1.0.0")]
60 use core::iter::FromIterator;
62 use core::ops::{self, Add, AddAssign, Index, IndexMut};
64 use core::str::pattern::Pattern;
65 use rustc_unicode::char::{decode_utf16, REPLACEMENT_CHARACTER};
66 use rustc_unicode::str as unicode_str;
68 use borrow::{Cow, ToOwned};
69 use range::RangeArgument;
70 use str::{self, FromStr, Utf8Error, Chars};
74 /// A UTF-8 encoded, growable string.
76 /// The `String` type is the most common string type that has ownership over the
77 /// contents of the string. It has a close relationship with its borrowed
78 /// counterpart, the primitive [`str`].
80 /// [`str`]: ../../std/primitive.str.html
84 /// You can create a `String` from a literal string with `String::from`:
87 /// let hello = String::from("Hello, world!");
90 /// You can append a [`char`] to a `String` with the [`push()`] method, and
91 /// append a [`&str`] with the [`push_str()`] method:
94 /// let mut hello = String::from("Hello, ");
97 /// hello.push_str("orld!");
100 /// [`char`]: ../../std/primitive.char.html
101 /// [`push()`]: #method.push
102 /// [`push_str()`]: #method.push_str
104 /// If you have a vector of UTF-8 bytes, you can create a `String` from it with
105 /// the [`from_utf8()`] method:
108 /// // some bytes, in a vector
109 /// let sparkle_heart = vec![240, 159, 146, 150];
111 /// // We know these bytes are valid, so we'll use `unwrap()`.
112 /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
114 /// assert_eq!("💖", sparkle_heart);
117 /// [`from_utf8()`]: #method.from_utf8
121 /// `String`s are always valid UTF-8. This has a few implications, the first of
122 /// which is that if you need a non-UTF-8 string, consider [`OsString`]. It is
123 /// similar, but without the UTF-8 constraint. The second implication is that
124 /// you cannot index into a `String`:
129 /// println!("The first letter of s is {}", s[0]); // ERROR!!!
132 /// [`OsString`]: ../../std/ffi/struct.OsString.html
134 /// Indexing is intended to be a constant-time operation, but UTF-8 encoding
135 /// does not allow us to do this. Furtheremore, it's not clear what sort of
136 /// thing the index should return: a byte, a codepoint, or a grapheme cluster.
137 /// The [`as_bytes()`] and [`chars()`] methods return iterators over the first
138 /// two, respectively.
140 /// [`as_bytes()`]: #method.as_bytes
141 /// [`chars()`]: #method.chars
145 /// `String`s implement [`Deref`]`<Target=str>`, and so inherit all of [`str`]'s
146 /// methods. In addition, this means that you can pass a `String` to any
147 /// function which takes a [`&str`] by using an ampersand (`&`):
150 /// fn takes_str(s: &str) { }
152 /// let s = String::from("Hello");
157 /// [`&str`]: ../../std/primitive.str.html
158 /// [`Deref`]: ../../std/ops/trait.Deref.html
160 /// This will create a [`&str`] from the `String` and pass it in. This
161 /// conversion is very inexpensive, and so generally, functions will accept
162 /// [`&str`]s as arguments unless they need a `String` for some specific reason.
167 /// A `String` is made up of three components: a pointer to some bytes, a
168 /// length, and a capacity. The pointer points to an internal buffer `String`
169 /// uses to store its data. The length is the number of bytes currently stored
170 /// in the buffer, and the capacity is the size of the buffer in bytes. As such,
171 /// the length will always be less than or equal to the capacity.
173 /// This buffer is always stored on the heap.
175 /// You can look at these with the [`as_ptr()`], [`len()`], and [`capacity()`]
181 /// let story = String::from("Once upon a time...");
183 /// let ptr = story.as_ptr();
184 /// let len = story.len();
185 /// let capacity = story.capacity();
187 /// // story has nineteen bytes
188 /// assert_eq!(19, len);
190 /// // Now that we have our parts, we throw the story away.
191 /// mem::forget(story);
193 /// // We can re-build a String out of ptr, len, and capacity. This is all
194 /// // unsafe because we are responsible for making sure the components are
196 /// let s = unsafe { String::from_raw_parts(ptr as *mut _, len, capacity) } ;
198 /// assert_eq!(String::from("Once upon a time..."), s);
201 /// [`as_ptr()`]: #method.as_ptr
202 /// [`len()`]: #method.len
203 /// [`capacity()`]: #method.capacity
205 /// If a `String` has enough capacity, adding elements to it will not
206 /// re-allocate. For example, consider this program:
209 /// let mut s = String::new();
211 /// println!("{}", s.capacity());
214 /// s.push_str("hello");
215 /// println!("{}", s.capacity());
219 /// This will output the following:
230 /// At first, we have no memory allocated at all, but as we append to the
231 /// string, it increases its capacity appropriately. If we instead use the
232 /// [`with_capacity()`] method to allocate the correct capacity initially:
235 /// let mut s = String::with_capacity(25);
237 /// println!("{}", s.capacity());
240 /// s.push_str("hello");
241 /// println!("{}", s.capacity());
245 /// [`with_capacity()`]: #method.with_capacity
247 /// We end up with a different output:
258 /// Here, there's no need to allocate more memory inside the loop.
259 #[derive(PartialOrd, Eq, Ord)]
260 #[stable(feature = "rust1", since = "1.0.0")]
265 /// A possible error value when converting a `String` from a UTF-8 byte vector.
267 /// This type is the error type for the [`from_utf8()`] method on [`String`]. It
268 /// is designed in such a way to carefully avoid reallocations: the
269 /// [`into_bytes()`] method will give back the byte vector that was used in the
270 /// conversion attempt.
272 /// [`from_utf8()`]: struct.String.html#method.from_utf8
273 /// [`String`]: struct.String.html
274 /// [`into_bytes()`]: struct.FromUtf8Error.html#method.into_bytes
276 /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
277 /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
278 /// an analogue to `FromUtf8Error`, and you can get one from a `FromUtf8Error`
279 /// through the [`utf8_error()`] method.
281 /// [`Utf8Error`]: ../../std/str/struct.Utf8Error.html
282 /// [`std::str`]: ../../std/str/index.html
283 /// [`u8`]: ../../std/primitive.u8.html
284 /// [`&str`]: ../../std/primitive.str.html
285 /// [`utf8_error()`]: #method.utf8_error
292 /// // some invalid bytes, in a vector
293 /// let bytes = vec![0, 159];
295 /// let value = String::from_utf8(bytes);
297 /// assert!(value.is_err());
298 /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
300 #[stable(feature = "rust1", since = "1.0.0")]
302 pub struct FromUtf8Error {
307 /// A possible error value when converting a `String` from a UTF-16 byte slice.
309 /// This type is the error type for the [`from_utf16()`] method on [`String`].
311 /// [`from_utf16()`]: struct.String.html#method.from_utf16
312 /// [`String`]: struct.String.html
319 /// // 𝄞mu<invalid>ic
320 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
321 /// 0xD800, 0x0069, 0x0063];
323 /// assert!(String::from_utf16(v).is_err());
325 #[stable(feature = "rust1", since = "1.0.0")]
327 pub struct FromUtf16Error(());
330 /// Creates a new empty `String`.
332 /// Given that the `String` is empty, this will not allocate any initial
333 /// buffer. While that means that this initial operation is very
334 /// inexpensive, but may cause excessive allocation later, when you add
335 /// data. If you have an idea of how much data the `String` will hold,
336 /// consider the [`with_capacity()`] method to prevent excessive
339 /// [`with_capacity()`]: #method.with_capacity
346 /// let s = String::new();
349 #[stable(feature = "rust1", since = "1.0.0")]
350 pub fn new() -> String {
351 String { vec: Vec::new() }
354 /// Creates a new empty `String` with a particular capacity.
356 /// `String`s have an internal buffer to hold their data. The capacity is
357 /// the length of that buffer, and can be queried with the [`capacity()`]
358 /// method. This method creates an empty `String`, but one with an initial
359 /// buffer that can hold `capacity` bytes. This is useful when you may be
360 /// appending a bunch of data to the `String`, reducing the number of
361 /// reallocations it needs to do.
363 /// [`capacity()`]: #method.capacity
365 /// If the given capacity is `0`, no allocation will occur, and this method
366 /// is identical to the [`new()`] method.
368 /// [`new()`]: #method.new
375 /// let mut s = String::with_capacity(10);
377 /// // The String contains no chars, even though it has capacity for more
378 /// assert_eq!(s.len(), 0);
380 /// // These are all done without reallocating...
381 /// let cap = s.capacity();
386 /// assert_eq!(s.capacity(), cap);
388 /// // ...but this may make the vector reallocate
392 #[stable(feature = "rust1", since = "1.0.0")]
393 pub fn with_capacity(capacity: usize) -> String {
394 String { vec: Vec::with_capacity(capacity) }
397 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
398 // required for this method definition, is not available. Since we don't
399 // require this method for testing purposes, I'll just stub it
400 // NB see the slice::hack module in slice.rs for more information
403 pub fn from_str(_: &str) -> String {
404 panic!("not available with cfg(test)");
407 /// Converts a vector of bytes to a `String`.
409 /// A string slice ([`&str`]) is made of bytes ([`u8`]), and a vector of bytes
410 /// ([`Vec<u8>`]) is made of bytes, so this function converts between the
411 /// two. Not all byte slices are valid `String`s, however: `String`
412 /// requires that it is valid UTF-8. `from_utf8()` checks to ensure that
413 /// the bytes are valid UTF-8, and then does the conversion.
415 /// [`&str`]: ../../std/primitive.str.html
416 /// [`u8`]: ../../std/primitive.u8.html
417 /// [`Vec<u8>`]: ../../std/vec/struct.Vec.html
419 /// If you are sure that the byte slice is valid UTF-8, and you don't want
420 /// to incur the overhead of the validity check, there is an unsafe version
421 /// of this function, [`from_utf8_unchecked()`], which has the same behavior
422 /// but skips the check.
424 /// [`from_utf8_unchecked()`]: struct.String.html#method.from_utf8_unchecked
426 /// This method will take care to not copy the vector, for efficiency's
429 /// If you need a `&str` instead of a `String`, consider
430 /// [`str::from_utf8()`].
432 /// [`str::from_utf8()`]: ../../std/str/fn.from_utf8.html
436 /// Returns `Err` if the slice is not UTF-8 with a description as to why the
437 /// provided bytes are not UTF-8. The vector you moved in is also included.
444 /// // some bytes, in a vector
445 /// let sparkle_heart = vec![240, 159, 146, 150];
447 /// // We know these bytes are valid, so we'll use `unwrap()`.
448 /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
450 /// assert_eq!("💖", sparkle_heart);
456 /// // some invalid bytes, in a vector
457 /// let sparkle_heart = vec![0, 159, 146, 150];
459 /// assert!(String::from_utf8(sparkle_heart).is_err());
462 /// See the docs for [`FromUtf8Error`] for more details on what you can do
465 /// [`FromUtf8Error`]: struct.FromUtf8Error.html
467 #[stable(feature = "rust1", since = "1.0.0")]
468 pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error> {
469 match str::from_utf8(&vec) {
470 Ok(..) => Ok(String { vec: vec }),
480 /// Converts a slice of bytes to a string, including invalid characters.
482 /// Strings are made of bytes ([`u8`]), and a slice of bytes
483 /// ([`&[u8]`][byteslice]) is made of bytes, so this function converts
484 /// between the two. Not all byte slices are valid strings, however: strings
485 /// are required to be valid UTF-8. During this conversion,
486 /// `from_utf8_lossy()` will replace any invalid UTF-8 sequences with
487 /// `U+FFFD REPLACEMENT CHARACTER`, which looks like this: �
489 /// [`u8`]: ../../std/primitive.u8.html
490 /// [byteslice]: ../../std/primitive.slice.html
492 /// If you are sure that the byte slice is valid UTF-8, and you don't want
493 /// to incur the overhead of the conversion, there is an unsafe version
494 /// of this function, [`from_utf8_unchecked()`], which has the same behavior
495 /// but skips the checks.
497 /// [`from_utf8_unchecked()`]: struct.String.html#method.from_utf8_unchecked
499 /// This function returns a [`Cow<'a, str>`]. If our byte slice is invalid
500 /// UTF-8, then we need to insert the replacement characters, which will
501 /// change the size of the string, and hence, require a `String`. But if
502 /// it's already valid UTF-8, we don't need a new allocation. This return
503 /// type allows us to handle both cases.
505 /// [`Cow<'a, str>`]: ../../std/borrow/enum.Cow.html
512 /// // some bytes, in a vector
513 /// let sparkle_heart = vec![240, 159, 146, 150];
515 /// let sparkle_heart = String::from_utf8_lossy(&sparkle_heart);
517 /// assert_eq!("💖", sparkle_heart);
523 /// // some invalid bytes
524 /// let input = b"Hello \xF0\x90\x80World";
525 /// let output = String::from_utf8_lossy(input);
527 /// assert_eq!("Hello �World", output);
529 #[stable(feature = "rust1", since = "1.0.0")]
530 pub fn from_utf8_lossy<'a>(v: &'a [u8]) -> Cow<'a, str> {
532 match str::from_utf8(v) {
533 Ok(s) => return Cow::Borrowed(s),
534 Err(e) => i = e.valid_up_to(),
537 const TAG_CONT_U8: u8 = 128;
538 const REPLACEMENT: &'static [u8] = b"\xEF\xBF\xBD"; // U+FFFD in UTF-8
540 fn unsafe_get(xs: &[u8], i: usize) -> u8 {
541 unsafe { *xs.get_unchecked(i) }
543 fn safe_get(xs: &[u8], i: usize, total: usize) -> u8 {
551 let mut res = String::with_capacity(total);
554 unsafe { res.as_mut_vec().extend_from_slice(&v[..i]) };
557 // subseqidx is the index of the first byte of the subsequence we're
558 // looking at. It's used to copy a bunch of contiguous good codepoints
559 // at once instead of copying them one by one.
560 let mut subseqidx = i;
564 let byte = unsafe_get(v, i);
567 macro_rules! error { () => ({
570 res.as_mut_vec().extend_from_slice(&v[subseqidx..i_]);
573 res.as_mut_vec().extend_from_slice(REPLACEMENT);
578 // subseqidx handles this
580 let w = unicode_str::utf8_char_width(byte);
584 if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
591 match (byte, safe_get(v, i, total)) {
592 (0xE0, 0xA0...0xBF) => (),
593 (0xE1...0xEC, 0x80...0xBF) => (),
594 (0xED, 0x80...0x9F) => (),
595 (0xEE...0xEF, 0x80...0xBF) => (),
602 if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
609 match (byte, safe_get(v, i, total)) {
610 (0xF0, 0x90...0xBF) => (),
611 (0xF1...0xF3, 0x80...0xBF) => (),
612 (0xF4, 0x80...0x8F) => (),
619 if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
624 if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
637 if subseqidx < total {
638 unsafe { res.as_mut_vec().extend_from_slice(&v[subseqidx..total]) };
643 /// Decode a UTF-16 encoded vector `v` into a `String`, returning `Err`
644 /// if `v` contains any invalid data.
652 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
653 /// 0x0073, 0x0069, 0x0063];
654 /// assert_eq!(String::from("𝄞music"),
655 /// String::from_utf16(v).unwrap());
657 /// // 𝄞mu<invalid>ic
658 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
659 /// 0xD800, 0x0069, 0x0063];
660 /// assert!(String::from_utf16(v).is_err());
662 #[stable(feature = "rust1", since = "1.0.0")]
663 pub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error> {
664 decode_utf16(v.iter().cloned()).collect::<Result<_, _>>().map_err(|_| FromUtf16Error(()))
667 /// Decode a UTF-16 encoded vector `v` into a string, replacing
668 /// invalid data with the replacement character (U+FFFD).
675 /// // 𝄞mus<invalid>ic<invalid>
676 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
677 /// 0x0073, 0xDD1E, 0x0069, 0x0063,
680 /// assert_eq!(String::from("𝄞mus\u{FFFD}ic\u{FFFD}"),
681 /// String::from_utf16_lossy(v));
684 #[stable(feature = "rust1", since = "1.0.0")]
685 pub fn from_utf16_lossy(v: &[u16]) -> String {
686 decode_utf16(v.iter().cloned()).map(|r| r.unwrap_or(REPLACEMENT_CHARACTER)).collect()
689 /// Creates a new `String` from a length, capacity, and pointer.
693 /// This is highly unsafe, due to the number of invariants that aren't
696 /// * The memory at `ptr` needs to have been previously allocated by the
697 /// same allocator the standard library uses.
698 /// * `length` needs to be less than or equal to `capacity`.
699 /// * `capacity` needs to be the correct value.
701 /// Violating these may cause problems like corrupting the allocator's
702 /// internal datastructures.
704 /// The ownership of `ptr` is effectively transferred to the
705 /// `String` which may then deallocate, reallocate or change the
706 /// contents of memory pointed to by the pointer at will. Ensure
707 /// that nothing else uses the pointer after calling this
718 /// let s = String::from("hello");
719 /// let ptr = s.as_ptr();
720 /// let len = s.len();
721 /// let capacity = s.capacity();
725 /// let s = String::from_raw_parts(ptr as *mut _, len, capacity);
727 /// assert_eq!(String::from("hello"), s);
731 #[stable(feature = "rust1", since = "1.0.0")]
732 pub unsafe fn from_raw_parts(buf: *mut u8, length: usize, capacity: usize) -> String {
733 String { vec: Vec::from_raw_parts(buf, length, capacity) }
736 /// Converts a vector of bytes to a `String` without checking that the
737 /// string contains valid UTF-8.
739 /// See the safe version, [`from_utf8()`], for more details.
741 /// [`from_utf8()`]: struct.String.html#method.from_utf8
745 /// This function is unsafe because it does not check that the bytes passed
746 /// to it are valid UTF-8. If this constraint is violated, it may cause
747 /// memory unsafety issues with future users of the `String`, as the rest of
748 /// the standard library assumes that `String`s are valid UTF-8.
755 /// // some bytes, in a vector
756 /// let sparkle_heart = vec![240, 159, 146, 150];
758 /// let sparkle_heart = unsafe {
759 /// String::from_utf8_unchecked(sparkle_heart)
762 /// assert_eq!("💖", sparkle_heart);
765 #[stable(feature = "rust1", since = "1.0.0")]
766 pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String {
767 String { vec: bytes }
770 /// Converts a `String` into a byte vector.
772 /// This consumes the `String`, so we do not need to copy its contents.
779 /// let s = String::from("hello");
780 /// let bytes = s.into_bytes();
782 /// assert_eq!(&[104, 101, 108, 108, 111][..], &bytes[..]);
785 #[stable(feature = "rust1", since = "1.0.0")]
786 pub fn into_bytes(self) -> Vec<u8> {
790 /// Extracts a string slice containing the entire string.
792 #[stable(feature = "string_as_str", since = "1.7.0")]
793 pub fn as_str(&self) -> &str {
797 /// Extracts a string slice containing the entire string.
799 #[stable(feature = "string_as_str", since = "1.7.0")]
800 pub fn as_mut_str(&mut self) -> &mut str {
804 /// Appends a given string slice onto the end of this `String`.
811 /// let mut s = String::from("foo");
813 /// s.push_str("bar");
815 /// assert_eq!("foobar", s);
818 #[stable(feature = "rust1", since = "1.0.0")]
819 pub fn push_str(&mut self, string: &str) {
820 self.vec.extend_from_slice(string.as_bytes())
823 /// Returns this `String`'s capacity, in bytes.
830 /// let s = String::with_capacity(10);
832 /// assert!(s.capacity() >= 10);
835 #[stable(feature = "rust1", since = "1.0.0")]
836 pub fn capacity(&self) -> usize {
840 /// Ensures that this `String`'s capacity is at least `additional` bytes
841 /// larger than its length.
843 /// The capacity may be increased by more than `additional` bytes if it
844 /// chooses, to prevent frequent reallocations.
846 /// If you do not want this "at least" behavior, see the [`reserve_exact()`]
849 /// [`reserve_exact()`]: #method.reserve_exact
853 /// Panics if the new capacity overflows `usize`.
860 /// let mut s = String::new();
864 /// assert!(s.capacity() >= 10);
867 /// This may not actually increase the capacity:
870 /// let mut s = String::with_capacity(10);
874 /// // s now has a length of 2 and a capacity of 10
875 /// assert_eq!(2, s.len());
876 /// assert_eq!(10, s.capacity());
878 /// // Since we already have an extra 8 capacity, calling this...
881 /// // ... doesn't actually increase.
882 /// assert_eq!(10, s.capacity());
885 #[stable(feature = "rust1", since = "1.0.0")]
886 pub fn reserve(&mut self, additional: usize) {
887 self.vec.reserve(additional)
890 /// Ensures that this `String`'s capacity is `additional` bytes
891 /// larger than its length.
893 /// Consider using the [`reserve()`] method unless you absolutely know
894 /// better than the allocator.
896 /// [`reserve()`]: #method.reserve
900 /// Panics if the new capacity overflows `usize`.
907 /// let mut s = String::new();
909 /// s.reserve_exact(10);
911 /// assert!(s.capacity() >= 10);
914 /// This may not actually increase the capacity:
917 /// let mut s = String::with_capacity(10);
921 /// // s now has a length of 2 and a capacity of 10
922 /// assert_eq!(2, s.len());
923 /// assert_eq!(10, s.capacity());
925 /// // Since we already have an extra 8 capacity, calling this...
926 /// s.reserve_exact(8);
928 /// // ... doesn't actually increase.
929 /// assert_eq!(10, s.capacity());
932 #[stable(feature = "rust1", since = "1.0.0")]
933 pub fn reserve_exact(&mut self, additional: usize) {
934 self.vec.reserve_exact(additional)
937 /// Shrinks the capacity of this `String` to match its length.
944 /// let mut s = String::from("foo");
947 /// assert!(s.capacity() >= 100);
949 /// s.shrink_to_fit();
950 /// assert_eq!(3, s.capacity());
953 #[stable(feature = "rust1", since = "1.0.0")]
954 pub fn shrink_to_fit(&mut self) {
955 self.vec.shrink_to_fit()
958 /// Appends the given `char` to the end of this `String`.
965 /// let mut s = String::from("abc");
971 /// assert_eq!("abc123", s);
974 #[stable(feature = "rust1", since = "1.0.0")]
975 pub fn push(&mut self, ch: char) {
976 match ch.len_utf8() {
977 1 => self.vec.push(ch as u8),
978 _ => self.vec.extend_from_slice(ch.encode_utf8().as_slice()),
982 /// Returns a byte slice of this `String`'s contents.
989 /// let s = String::from("hello");
991 /// assert_eq!(&[104, 101, 108, 108, 111], s.as_bytes());
994 #[stable(feature = "rust1", since = "1.0.0")]
995 pub fn as_bytes(&self) -> &[u8] {
999 /// Shortens this `String` to the specified length.
1001 /// If `new_len` is greater than the string's current length, this has no
1006 /// Panics if `new_len` does not lie on a [`char`] boundary.
1008 /// [`char`]: ../../std/primitive.char.html
1015 /// let mut s = String::from("hello");
1019 /// assert_eq!("he", s);
1022 #[stable(feature = "rust1", since = "1.0.0")]
1023 pub fn truncate(&mut self, new_len: usize) {
1024 if new_len <= self.len() {
1025 assert!(self.is_char_boundary(new_len));
1026 self.vec.truncate(new_len)
1030 /// Removes the last character from the string buffer and returns it.
1032 /// Returns `None` if this `String` is empty.
1039 /// let mut s = String::from("foo");
1041 /// assert_eq!(s.pop(), Some('o'));
1042 /// assert_eq!(s.pop(), Some('o'));
1043 /// assert_eq!(s.pop(), Some('f'));
1045 /// assert_eq!(s.pop(), None);
1048 #[stable(feature = "rust1", since = "1.0.0")]
1049 pub fn pop(&mut self) -> Option<char> {
1050 let ch = match self.chars().rev().next() {
1052 None => return None,
1054 let newlen = self.len() - ch.len_utf8();
1056 self.vec.set_len(newlen);
1061 /// Removes a `char` from this `String` at a byte position and returns it.
1063 /// This is an `O(n)` operation, as it requires copying every element in the
1068 /// Panics if `idx` is larger than or equal to the `String`'s length,
1069 /// or if it does not lie on a [`char`] boundary.
1071 /// [`char`]: ../../std/primitive.char.html
1078 /// let mut s = String::from("foo");
1080 /// assert_eq!(s.remove(0), 'f');
1081 /// assert_eq!(s.remove(1), 'o');
1082 /// assert_eq!(s.remove(0), 'o');
1085 #[stable(feature = "rust1", since = "1.0.0")]
1086 pub fn remove(&mut self, idx: usize) -> char {
1087 let ch = match self[idx..].chars().next() {
1089 None => panic!("cannot remove a char from the end of a string"),
1092 let next = idx + ch.len_utf8();
1093 let len = self.len();
1095 ptr::copy(self.vec.as_ptr().offset(next as isize),
1096 self.vec.as_mut_ptr().offset(idx as isize),
1098 self.vec.set_len(len - (next - idx));
1103 /// Inserts a character into this `String` at a byte position.
1105 /// This is an `O(n)` operation as it requires copying every element in the
1110 /// Panics if `idx` is larger than the `String`'s length, or if it does not
1111 /// lie on a [`char`] boundary.
1113 /// [`char`]: ../../std/primitive.char.html
1120 /// let mut s = String::with_capacity(3);
1122 /// s.insert(0, 'f');
1123 /// s.insert(1, 'o');
1124 /// s.insert(2, 'o');
1126 /// assert_eq!("foo", s);
1129 #[stable(feature = "rust1", since = "1.0.0")]
1130 pub fn insert(&mut self, idx: usize, ch: char) {
1131 let len = self.len();
1132 assert!(idx <= len);
1133 assert!(self.is_char_boundary(idx));
1134 let bits = ch.encode_utf8();
1137 self.insert_bytes(idx, bits.as_slice());
1141 unsafe fn insert_bytes(&mut self, idx: usize, bytes: &[u8]) {
1142 let len = self.len();
1143 let amt = bytes.len();
1144 self.vec.reserve(amt);
1146 ptr::copy(self.vec.as_ptr().offset(idx as isize),
1147 self.vec.as_mut_ptr().offset((idx + amt) as isize),
1149 ptr::copy(bytes.as_ptr(),
1150 self.vec.as_mut_ptr().offset(idx as isize),
1152 self.vec.set_len(len + amt);
1155 /// Inserts a string slice into this `String` at a byte position.
1157 /// This is an `O(n)` operation as it requires copying every element in the
1162 /// Panics if `idx` is larger than the `String`'s length, or if it does not
1163 /// lie on a [`char`] boundary.
1165 /// [`char`]: ../../std/primitive.char.html
1172 /// #![feature(insert_str)]
1174 /// let mut s = String::from("bar");
1176 /// s.insert_str(0, "foo");
1178 /// assert_eq!("foobar", s);
1181 #[unstable(feature = "insert_str",
1182 reason = "recent addition",
1184 pub fn insert_str(&mut self, idx: usize, string: &str) {
1185 let len = self.len();
1186 assert!(idx <= len);
1187 assert!(self.is_char_boundary(idx));
1190 self.insert_bytes(idx, string.as_bytes());
1194 /// Returns a mutable reference to the contents of this `String`.
1198 /// This function is unsafe because it does not check that the bytes passed
1199 /// to it are valid UTF-8. If this constraint is violated, it may cause
1200 /// memory unsafety issues with future users of the `String`, as the rest of
1201 /// the standard library assumes that `String`s are valid UTF-8.
1208 /// let mut s = String::from("hello");
1211 /// let vec = s.as_mut_vec();
1212 /// assert_eq!(&[104, 101, 108, 108, 111][..], &vec[..]);
1216 /// assert_eq!(s, "olleh");
1219 #[stable(feature = "rust1", since = "1.0.0")]
1220 pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1224 /// Returns the length of this `String`, in bytes.
1231 /// let a = String::from("foo");
1233 /// assert_eq!(a.len(), 3);
1236 #[stable(feature = "rust1", since = "1.0.0")]
1237 pub fn len(&self) -> usize {
1241 /// Returns `true` if this `String` has a length of zero.
1243 /// Returns `false` otherwise.
1250 /// let mut v = String::new();
1251 /// assert!(v.is_empty());
1254 /// assert!(!v.is_empty());
1257 #[stable(feature = "rust1", since = "1.0.0")]
1258 pub fn is_empty(&self) -> bool {
1262 /// Truncates this `String`, removing all contents.
1264 /// While this means the `String` will have a length of zero, it does not
1265 /// touch its capacity.
1272 /// let mut s = String::from("foo");
1276 /// assert!(s.is_empty());
1277 /// assert_eq!(0, s.len());
1278 /// assert_eq!(3, s.capacity());
1281 #[stable(feature = "rust1", since = "1.0.0")]
1282 pub fn clear(&mut self) {
1286 /// Create a draining iterator that removes the specified range in the string
1287 /// and yields the removed chars.
1289 /// Note: The element range is removed even if the iterator is not
1290 /// consumed until the end.
1294 /// Panics if the starting point or end point do not lie on a [`char`]
1295 /// boundary, or if they're out of bounds.
1297 /// [`char`]: ../../std/primitive.char.html
1304 /// let mut s = String::from("α is alpha, β is beta");
1305 /// let beta_offset = s.find('β').unwrap_or(s.len());
1307 /// // Remove the range up until the β from the string
1308 /// let t: String = s.drain(..beta_offset).collect();
1309 /// assert_eq!(t, "α is alpha, ");
1310 /// assert_eq!(s, "β is beta");
1312 /// // A full range clears the string
1314 /// assert_eq!(s, "");
1316 #[stable(feature = "drain", since = "1.6.0")]
1317 pub fn drain<R>(&mut self, range: R) -> Drain
1318 where R: RangeArgument<usize>
1322 // The String version of Drain does not have the memory safety issues
1323 // of the vector version. The data is just plain bytes.
1324 // Because the range removal happens in Drop, if the Drain iterator is leaked,
1325 // the removal will not happen.
1326 let len = self.len();
1327 let start = *range.start().unwrap_or(&0);
1328 let end = *range.end().unwrap_or(&len);
1330 // Take out two simultaneous borrows. The &mut String won't be accessed
1331 // until iteration is over, in Drop.
1332 let self_ptr = self as *mut _;
1333 // slicing does the appropriate bounds checks
1334 let chars_iter = self[start..end].chars();
1344 /// Converts this `String` into a `Box<str>`.
1346 /// This will drop any excess capacity.
1353 /// let s = String::from("hello");
1355 /// let b = s.into_boxed_str();
1357 #[stable(feature = "box_str", since = "1.4.0")]
1358 pub fn into_boxed_str(self) -> Box<str> {
1359 let slice = self.vec.into_boxed_slice();
1360 unsafe { mem::transmute::<Box<[u8]>, Box<str>>(slice) }
1364 impl FromUtf8Error {
1365 /// Returns the bytes that were attempted to convert to a `String`.
1367 /// This method is carefully constructed to avoid allocation. It will
1368 /// consume the error, moving out the bytes, so that a copy of the bytes
1369 /// does not need to be made.
1376 /// // some invalid bytes, in a vector
1377 /// let bytes = vec![0, 159];
1379 /// let value = String::from_utf8(bytes);
1381 /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
1383 #[stable(feature = "rust1", since = "1.0.0")]
1384 pub fn into_bytes(self) -> Vec<u8> {
1388 /// Fetch a `Utf8Error` to get more details about the conversion failure.
1390 /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
1391 /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
1392 /// an analogue to `FromUtf8Error`. See its documentation for more details
1395 /// [`Utf8Error`]: ../../std/str/struct.Utf8Error.html
1396 /// [`std::str`]: ../../std/str/index.html
1397 /// [`u8`]: ../../std/primitive.u8.html
1398 /// [`&str`]: ../../std/primitive.str.html
1405 /// // some invalid bytes, in a vector
1406 /// let bytes = vec![0, 159];
1408 /// let error = String::from_utf8(bytes).unwrap_err().utf8_error();
1410 /// // the first byte is invalid here
1411 /// assert_eq!(1, error.valid_up_to());
1413 #[stable(feature = "rust1", since = "1.0.0")]
1414 pub fn utf8_error(&self) -> Utf8Error {
1419 #[stable(feature = "rust1", since = "1.0.0")]
1420 impl fmt::Display for FromUtf8Error {
1421 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1422 fmt::Display::fmt(&self.error, f)
1426 #[stable(feature = "rust1", since = "1.0.0")]
1427 impl fmt::Display for FromUtf16Error {
1428 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1429 fmt::Display::fmt("invalid utf-16: lone surrogate found", f)
1433 #[stable(feature = "rust1", since = "1.0.0")]
1434 impl Clone for String {
1435 fn clone(&self) -> Self {
1436 String { vec: self.vec.clone() }
1439 fn clone_from(&mut self, source: &Self) {
1440 self.vec.clone_from(&source.vec);
1444 #[stable(feature = "rust1", since = "1.0.0")]
1445 impl FromIterator<char> for String {
1446 fn from_iter<I: IntoIterator<Item = char>>(iter: I) -> String {
1447 let mut buf = String::new();
1453 #[stable(feature = "rust1", since = "1.0.0")]
1454 impl<'a> FromIterator<&'a str> for String {
1455 fn from_iter<I: IntoIterator<Item = &'a str>>(iter: I) -> String {
1456 let mut buf = String::new();
1462 #[stable(feature = "extend_string", since = "1.4.0")]
1463 impl FromIterator<String> for String {
1464 fn from_iter<I: IntoIterator<Item = String>>(iter: I) -> String {
1465 let mut buf = String::new();
1471 #[stable(feature = "rust1", since = "1.0.0")]
1472 impl Extend<char> for String {
1473 fn extend<I: IntoIterator<Item = char>>(&mut self, iter: I) {
1474 let iterator = iter.into_iter();
1475 let (lower_bound, _) = iterator.size_hint();
1476 self.reserve(lower_bound);
1477 for ch in iterator {
1483 #[stable(feature = "extend_ref", since = "1.2.0")]
1484 impl<'a> Extend<&'a char> for String {
1485 fn extend<I: IntoIterator<Item = &'a char>>(&mut self, iter: I) {
1486 self.extend(iter.into_iter().cloned());
1490 #[stable(feature = "rust1", since = "1.0.0")]
1491 impl<'a> Extend<&'a str> for String {
1492 fn extend<I: IntoIterator<Item = &'a str>>(&mut self, iter: I) {
1499 #[stable(feature = "extend_string", since = "1.4.0")]
1500 impl Extend<String> for String {
1501 fn extend<I: IntoIterator<Item = String>>(&mut self, iter: I) {
1508 /// A convenience impl that delegates to the impl for `&str`
1509 #[unstable(feature = "pattern",
1510 reason = "API not fully fleshed out and ready to be stabilized",
1512 impl<'a, 'b> Pattern<'a> for &'b String {
1513 type Searcher = <&'b str as Pattern<'a>>::Searcher;
1515 fn into_searcher(self, haystack: &'a str) -> <&'b str as Pattern<'a>>::Searcher {
1516 self[..].into_searcher(haystack)
1520 fn is_contained_in(self, haystack: &'a str) -> bool {
1521 self[..].is_contained_in(haystack)
1525 fn is_prefix_of(self, haystack: &'a str) -> bool {
1526 self[..].is_prefix_of(haystack)
1530 #[stable(feature = "rust1", since = "1.0.0")]
1531 impl PartialEq for String {
1533 fn eq(&self, other: &String) -> bool {
1534 PartialEq::eq(&self[..], &other[..])
1537 fn ne(&self, other: &String) -> bool {
1538 PartialEq::ne(&self[..], &other[..])
1542 macro_rules! impl_eq {
1543 ($lhs:ty, $rhs: ty) => {
1544 #[stable(feature = "rust1", since = "1.0.0")]
1545 impl<'a, 'b> PartialEq<$rhs> for $lhs {
1547 fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
1549 fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
1552 #[stable(feature = "rust1", since = "1.0.0")]
1553 impl<'a, 'b> PartialEq<$lhs> for $rhs {
1555 fn eq(&self, other: &$lhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
1557 fn ne(&self, other: &$lhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
1563 impl_eq! { String, str }
1564 impl_eq! { String, &'a str }
1565 impl_eq! { Cow<'a, str>, str }
1566 impl_eq! { Cow<'a, str>, &'b str }
1567 impl_eq! { Cow<'a, str>, String }
1569 #[stable(feature = "rust1", since = "1.0.0")]
1570 impl Default for String {
1572 fn default() -> String {
1577 #[stable(feature = "rust1", since = "1.0.0")]
1578 impl fmt::Display for String {
1580 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1581 fmt::Display::fmt(&**self, f)
1585 #[stable(feature = "rust1", since = "1.0.0")]
1586 impl fmt::Debug for String {
1588 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1589 fmt::Debug::fmt(&**self, f)
1593 #[stable(feature = "rust1", since = "1.0.0")]
1594 impl hash::Hash for String {
1596 fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
1597 (**self).hash(hasher)
1601 #[stable(feature = "rust1", since = "1.0.0")]
1602 impl<'a> Add<&'a str> for String {
1603 type Output = String;
1606 fn add(mut self, other: &str) -> String {
1607 self.push_str(other);
1612 #[stable(feature = "stringaddassign", since = "1.12.0")]
1613 impl<'a> AddAssign<&'a str> for String {
1615 fn add_assign(&mut self, other: &str) {
1616 self.push_str(other);
1620 #[stable(feature = "rust1", since = "1.0.0")]
1621 impl ops::Index<ops::Range<usize>> for String {
1625 fn index(&self, index: ops::Range<usize>) -> &str {
1629 #[stable(feature = "rust1", since = "1.0.0")]
1630 impl ops::Index<ops::RangeTo<usize>> for String {
1634 fn index(&self, index: ops::RangeTo<usize>) -> &str {
1638 #[stable(feature = "rust1", since = "1.0.0")]
1639 impl ops::Index<ops::RangeFrom<usize>> for String {
1643 fn index(&self, index: ops::RangeFrom<usize>) -> &str {
1647 #[stable(feature = "rust1", since = "1.0.0")]
1648 impl ops::Index<ops::RangeFull> for String {
1652 fn index(&self, _index: ops::RangeFull) -> &str {
1653 unsafe { str::from_utf8_unchecked(&self.vec) }
1656 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1657 impl ops::Index<ops::RangeInclusive<usize>> for String {
1661 fn index(&self, index: ops::RangeInclusive<usize>) -> &str {
1662 Index::index(&**self, index)
1665 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1666 impl ops::Index<ops::RangeToInclusive<usize>> for String {
1670 fn index(&self, index: ops::RangeToInclusive<usize>) -> &str {
1671 Index::index(&**self, index)
1675 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1676 impl ops::IndexMut<ops::Range<usize>> for String {
1678 fn index_mut(&mut self, index: ops::Range<usize>) -> &mut str {
1679 &mut self[..][index]
1682 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1683 impl ops::IndexMut<ops::RangeTo<usize>> for String {
1685 fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut str {
1686 &mut self[..][index]
1689 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1690 impl ops::IndexMut<ops::RangeFrom<usize>> for String {
1692 fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut str {
1693 &mut self[..][index]
1696 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1697 impl ops::IndexMut<ops::RangeFull> for String {
1699 fn index_mut(&mut self, _index: ops::RangeFull) -> &mut str {
1700 unsafe { mem::transmute(&mut *self.vec) }
1703 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1704 impl ops::IndexMut<ops::RangeInclusive<usize>> for String {
1706 fn index_mut(&mut self, index: ops::RangeInclusive<usize>) -> &mut str {
1707 IndexMut::index_mut(&mut **self, index)
1710 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1711 impl ops::IndexMut<ops::RangeToInclusive<usize>> for String {
1713 fn index_mut(&mut self, index: ops::RangeToInclusive<usize>) -> &mut str {
1714 IndexMut::index_mut(&mut **self, index)
1718 #[stable(feature = "rust1", since = "1.0.0")]
1719 impl ops::Deref for String {
1723 fn deref(&self) -> &str {
1724 unsafe { str::from_utf8_unchecked(&self.vec) }
1728 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1729 impl ops::DerefMut for String {
1731 fn deref_mut(&mut self) -> &mut str {
1732 unsafe { mem::transmute(&mut *self.vec) }
1736 /// An error when parsing a `String`.
1738 /// This `enum` is slightly awkward: it will never actually exist. This error is
1739 /// part of the type signature of the implementation of [`FromStr`] on
1740 /// [`String`]. The return type of [`from_str()`], requires that an error be
1741 /// defined, but, given that a [`String`] can always be made into a new
1742 /// [`String`] without error, this type will never actually be returned. As
1743 /// such, it is only here to satisfy said signature, and is useless otherwise.
1745 /// [`FromStr`]: ../../std/str/trait.FromStr.html
1746 /// [`String`]: struct.String.html
1747 /// [`from_str()`]: ../../std/str/trait.FromStr.html#tymethod.from_str
1748 #[stable(feature = "str_parse_error", since = "1.5.0")]
1750 pub enum ParseError {}
1752 #[stable(feature = "rust1", since = "1.0.0")]
1753 impl FromStr for String {
1754 type Err = ParseError;
1756 fn from_str(s: &str) -> Result<String, ParseError> {
1761 #[stable(feature = "str_parse_error", since = "1.5.0")]
1762 impl Clone for ParseError {
1763 fn clone(&self) -> ParseError {
1768 #[stable(feature = "str_parse_error", since = "1.5.0")]
1769 impl fmt::Debug for ParseError {
1770 fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result {
1775 #[stable(feature = "str_parse_error2", since = "1.8.0")]
1776 impl fmt::Display for ParseError {
1777 fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result {
1782 #[stable(feature = "str_parse_error", since = "1.5.0")]
1783 impl PartialEq for ParseError {
1784 fn eq(&self, _: &ParseError) -> bool {
1789 #[stable(feature = "str_parse_error", since = "1.5.0")]
1790 impl Eq for ParseError {}
1792 /// A trait for converting a value to a `String`.
1794 /// This trait is automatically implemented for any type which implements the
1795 /// [`Display`] trait. As such, `ToString` shouldn't be implemented directly:
1796 /// [`Display`] should be implemented instead, and you get the `ToString`
1797 /// implementation for free.
1799 /// [`Display`]: ../../std/fmt/trait.Display.html
1800 #[stable(feature = "rust1", since = "1.0.0")]
1801 pub trait ToString {
1802 /// Converts the given value to a `String`.
1810 /// let five = String::from("5");
1812 /// assert_eq!(five, i.to_string());
1814 #[stable(feature = "rust1", since = "1.0.0")]
1815 fn to_string(&self) -> String;
1818 #[stable(feature = "rust1", since = "1.0.0")]
1819 impl<T: fmt::Display + ?Sized> ToString for T {
1821 default fn to_string(&self) -> String {
1822 use core::fmt::Write;
1823 let mut buf = String::new();
1824 let _ = buf.write_fmt(format_args!("{}", self));
1825 buf.shrink_to_fit();
1830 #[stable(feature = "str_to_string_specialization", since = "1.9.0")]
1831 impl ToString for str {
1833 fn to_string(&self) -> String {
1838 #[stable(feature = "rust1", since = "1.0.0")]
1839 impl AsRef<str> for String {
1841 fn as_ref(&self) -> &str {
1846 #[stable(feature = "rust1", since = "1.0.0")]
1847 impl AsRef<[u8]> for String {
1849 fn as_ref(&self) -> &[u8] {
1854 #[stable(feature = "rust1", since = "1.0.0")]
1855 impl<'a> From<&'a str> for String {
1856 fn from(s: &'a str) -> String {
1861 #[stable(feature = "rust1", since = "1.0.0")]
1862 impl<'a> From<&'a str> for Cow<'a, str> {
1864 fn from(s: &'a str) -> Cow<'a, str> {
1869 #[stable(feature = "rust1", since = "1.0.0")]
1870 impl<'a> From<String> for Cow<'a, str> {
1872 fn from(s: String) -> Cow<'a, str> {
1877 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
1878 impl<'a> FromIterator<char> for Cow<'a, str> {
1879 fn from_iter<I: IntoIterator<Item = char>>(it: I) -> Cow<'a, str> {
1880 Cow::Owned(FromIterator::from_iter(it))
1884 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
1885 impl<'a, 'b> FromIterator<&'b str> for Cow<'a, str> {
1886 fn from_iter<I: IntoIterator<Item = &'b str>>(it: I) -> Cow<'a, str> {
1887 Cow::Owned(FromIterator::from_iter(it))
1891 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
1892 impl<'a> FromIterator<String> for Cow<'a, str> {
1893 fn from_iter<I: IntoIterator<Item = String>>(it: I) -> Cow<'a, str> {
1894 Cow::Owned(FromIterator::from_iter(it))
1898 #[stable(feature = "rust1", since = "1.0.0")]
1899 impl Into<Vec<u8>> for String {
1900 fn into(self) -> Vec<u8> {
1905 #[stable(feature = "stringfromchars", since = "1.12.0")]
1906 impl<'a> From<&'a [char]> for String {
1908 fn from(v: &'a [char]) -> String {
1909 let mut s = String::with_capacity(v.len());
1917 #[stable(feature = "stringfromchars", since = "1.12.0")]
1918 impl From<Vec<char>> for String {
1920 fn from(v: Vec<char>) -> String {
1921 String::from(v.as_slice())
1925 #[stable(feature = "rust1", since = "1.0.0")]
1926 impl fmt::Write for String {
1928 fn write_str(&mut self, s: &str) -> fmt::Result {
1934 fn write_char(&mut self, c: char) -> fmt::Result {
1940 /// A draining iterator for `String`.
1942 /// This struct is created by the [`drain()`] method on [`String`]. See its
1943 /// documentation for more.
1945 /// [`drain()`]: struct.String.html#method.drain
1946 /// [`String`]: struct.String.html
1947 #[stable(feature = "drain", since = "1.6.0")]
1948 pub struct Drain<'a> {
1949 /// Will be used as &'a mut String in the destructor
1950 string: *mut String,
1951 /// Start of part to remove
1953 /// End of part to remove
1955 /// Current remaining range to remove
1959 #[stable(feature = "drain", since = "1.6.0")]
1960 unsafe impl<'a> Sync for Drain<'a> {}
1961 #[stable(feature = "drain", since = "1.6.0")]
1962 unsafe impl<'a> Send for Drain<'a> {}
1964 #[stable(feature = "drain", since = "1.6.0")]
1965 impl<'a> Drop for Drain<'a> {
1966 fn drop(&mut self) {
1968 // Use Vec::drain. "Reaffirm" the bounds checks to avoid
1969 // panic code being inserted again.
1970 let self_vec = (*self.string).as_mut_vec();
1971 if self.start <= self.end && self.end <= self_vec.len() {
1972 self_vec.drain(self.start..self.end);
1978 #[stable(feature = "drain", since = "1.6.0")]
1979 impl<'a> Iterator for Drain<'a> {
1983 fn next(&mut self) -> Option<char> {
1987 fn size_hint(&self) -> (usize, Option<usize>) {
1988 self.iter.size_hint()
1992 #[stable(feature = "drain", since = "1.6.0")]
1993 impl<'a> DoubleEndedIterator for Drain<'a> {
1995 fn next_back(&mut self) -> Option<char> {
1996 self.iter.next_back()