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::pattern::Pattern;
66 use std_unicode::char::{decode_utf16, REPLACEMENT_CHARACTER};
67 use std_unicode::str as unicode_str;
69 use borrow::{Cow, ToOwned};
70 use range::RangeArgument;
71 use str::{self, FromStr, Utf8Error, Chars};
75 /// A UTF-8 encoded, growable string.
77 /// The `String` type is the most common string type that has ownership over the
78 /// contents of the string. It has a close relationship with its borrowed
79 /// counterpart, the primitive [`str`].
81 /// [`str`]: ../../std/primitive.str.html
85 /// You can create a `String` from a literal string with `String::from`:
88 /// let hello = String::from("Hello, world!");
91 /// You can append a [`char`] to a `String` with the [`push()`] method, and
92 /// append a [`&str`] with the [`push_str()`] method:
95 /// let mut hello = String::from("Hello, ");
98 /// hello.push_str("orld!");
101 /// [`char`]: ../../std/primitive.char.html
102 /// [`push()`]: #method.push
103 /// [`push_str()`]: #method.push_str
105 /// If you have a vector of UTF-8 bytes, you can create a `String` from it with
106 /// the [`from_utf8()`] method:
109 /// // some bytes, in a vector
110 /// let sparkle_heart = vec![240, 159, 146, 150];
112 /// // We know these bytes are valid, so we'll use `unwrap()`.
113 /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
115 /// assert_eq!("💖", sparkle_heart);
118 /// [`from_utf8()`]: #method.from_utf8
122 /// `String`s are always valid UTF-8. This has a few implications, the first of
123 /// which is that if you need a non-UTF-8 string, consider [`OsString`]. It is
124 /// similar, but without the UTF-8 constraint. The second implication is that
125 /// you cannot index into a `String`:
130 /// println!("The first letter of s is {}", s[0]); // ERROR!!!
133 /// [`OsString`]: ../../std/ffi/struct.OsString.html
135 /// Indexing is intended to be a constant-time operation, but UTF-8 encoding
136 /// does not allow us to do this. Furthermore, it's not clear what sort of
137 /// thing the index should return: a byte, a codepoint, or a grapheme cluster.
138 /// The [`bytes()`] and [`chars()`] methods return iterators over the first
139 /// two, respectively.
141 /// [`bytes()`]: #method.bytes
142 /// [`chars()`]: #method.chars
146 /// `String`s implement [`Deref`]`<Target=str>`, and so inherit all of [`str`]'s
147 /// methods. In addition, this means that you can pass a `String` to any
148 /// function which takes a [`&str`] by using an ampersand (`&`):
151 /// fn takes_str(s: &str) { }
153 /// let s = String::from("Hello");
158 /// [`&str`]: ../../std/primitive.str.html
159 /// [`Deref`]: ../../std/ops/trait.Deref.html
161 /// This will create a [`&str`] from the `String` and pass it in. This
162 /// conversion is very inexpensive, and so generally, functions will accept
163 /// [`&str`]s as arguments unless they need a `String` for some specific reason.
168 /// A `String` is made up of three components: a pointer to some bytes, a
169 /// length, and a capacity. The pointer points to an internal buffer `String`
170 /// uses to store its data. The length is the number of bytes currently stored
171 /// in the buffer, and the capacity is the size of the buffer in bytes. As such,
172 /// the length will always be less than or equal to the capacity.
174 /// This buffer is always stored on the heap.
176 /// You can look at these with the [`as_ptr()`], [`len()`], and [`capacity()`]
182 /// let story = String::from("Once upon a time...");
184 /// let ptr = story.as_ptr();
185 /// let len = story.len();
186 /// let capacity = story.capacity();
188 /// // story has nineteen bytes
189 /// assert_eq!(19, len);
191 /// // Now that we have our parts, we throw the story away.
192 /// mem::forget(story);
194 /// // We can re-build a String out of ptr, len, and capacity. This is all
195 /// // unsafe because we are responsible for making sure the components are
197 /// let s = unsafe { String::from_raw_parts(ptr as *mut _, len, capacity) } ;
199 /// assert_eq!(String::from("Once upon a time..."), s);
202 /// [`as_ptr()`]: #method.as_ptr
203 /// [`len()`]: #method.len
204 /// [`capacity()`]: #method.capacity
206 /// If a `String` has enough capacity, adding elements to it will not
207 /// re-allocate. For example, consider this program:
210 /// let mut s = String::new();
212 /// println!("{}", s.capacity());
215 /// s.push_str("hello");
216 /// println!("{}", s.capacity());
220 /// This will output the following:
231 /// At first, we have no memory allocated at all, but as we append to the
232 /// string, it increases its capacity appropriately. If we instead use the
233 /// [`with_capacity()`] method to allocate the correct capacity initially:
236 /// let mut s = String::with_capacity(25);
238 /// println!("{}", s.capacity());
241 /// s.push_str("hello");
242 /// println!("{}", s.capacity());
246 /// [`with_capacity()`]: #method.with_capacity
248 /// We end up with a different output:
259 /// Here, there's no need to allocate more memory inside the loop.
260 #[derive(PartialOrd, Eq, Ord)]
261 #[stable(feature = "rust1", since = "1.0.0")]
266 /// A possible error value when converting a `String` from a UTF-8 byte vector.
268 /// This type is the error type for the [`from_utf8()`] method on [`String`]. It
269 /// is designed in such a way to carefully avoid reallocations: the
270 /// [`into_bytes()`] method will give back the byte vector that was used in the
271 /// conversion attempt.
273 /// [`from_utf8()`]: struct.String.html#method.from_utf8
274 /// [`String`]: struct.String.html
275 /// [`into_bytes()`]: struct.FromUtf8Error.html#method.into_bytes
277 /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
278 /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
279 /// an analogue to `FromUtf8Error`, and you can get one from a `FromUtf8Error`
280 /// through the [`utf8_error()`] method.
282 /// [`Utf8Error`]: ../../std/str/struct.Utf8Error.html
283 /// [`std::str`]: ../../std/str/index.html
284 /// [`u8`]: ../../std/primitive.u8.html
285 /// [`&str`]: ../../std/primitive.str.html
286 /// [`utf8_error()`]: #method.utf8_error
293 /// // some invalid bytes, in a vector
294 /// let bytes = vec![0, 159];
296 /// let value = String::from_utf8(bytes);
298 /// assert!(value.is_err());
299 /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
301 #[stable(feature = "rust1", since = "1.0.0")]
303 pub struct FromUtf8Error {
308 /// A possible error value when converting a `String` from a UTF-16 byte slice.
310 /// This type is the error type for the [`from_utf16()`] method on [`String`].
312 /// [`from_utf16()`]: struct.String.html#method.from_utf16
313 /// [`String`]: struct.String.html
320 /// // 𝄞mu<invalid>ic
321 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
322 /// 0xD800, 0x0069, 0x0063];
324 /// assert!(String::from_utf16(v).is_err());
326 #[stable(feature = "rust1", since = "1.0.0")]
328 pub struct FromUtf16Error(());
331 /// Creates a new empty `String`.
333 /// Given that the `String` is empty, this will not allocate any initial
334 /// buffer. While that means that this initial operation is very
335 /// inexpensive, but may cause excessive allocation later, when you add
336 /// data. If you have an idea of how much data the `String` will hold,
337 /// consider the [`with_capacity()`] method to prevent excessive
340 /// [`with_capacity()`]: #method.with_capacity
347 /// let s = String::new();
350 #[stable(feature = "rust1", since = "1.0.0")]
351 pub fn new() -> String {
352 String { vec: Vec::new() }
355 /// Creates a new empty `String` with a particular capacity.
357 /// `String`s have an internal buffer to hold their data. The capacity is
358 /// the length of that buffer, and can be queried with the [`capacity()`]
359 /// method. This method creates an empty `String`, but one with an initial
360 /// buffer that can hold `capacity` bytes. This is useful when you may be
361 /// appending a bunch of data to the `String`, reducing the number of
362 /// reallocations it needs to do.
364 /// [`capacity()`]: #method.capacity
366 /// If the given capacity is `0`, no allocation will occur, and this method
367 /// is identical to the [`new()`] method.
369 /// [`new()`]: #method.new
376 /// let mut s = String::with_capacity(10);
378 /// // The String contains no chars, even though it has capacity for more
379 /// assert_eq!(s.len(), 0);
381 /// // These are all done without reallocating...
382 /// let cap = s.capacity();
387 /// assert_eq!(s.capacity(), cap);
389 /// // ...but this may make the vector reallocate
393 #[stable(feature = "rust1", since = "1.0.0")]
394 pub fn with_capacity(capacity: usize) -> String {
395 String { vec: Vec::with_capacity(capacity) }
398 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
399 // required for this method definition, is not available. Since we don't
400 // require this method for testing purposes, I'll just stub it
401 // NB see the slice::hack module in slice.rs for more information
404 pub fn from_str(_: &str) -> String {
405 panic!("not available with cfg(test)");
408 /// Converts a vector of bytes to a `String`.
410 /// A string slice ([`&str`]) is made of bytes ([`u8`]), and a vector of bytes
411 /// ([`Vec<u8>`]) is made of bytes, so this function converts between the
412 /// two. Not all byte slices are valid `String`s, however: `String`
413 /// requires that it is valid UTF-8. `from_utf8()` checks to ensure that
414 /// the bytes are valid UTF-8, and then does the conversion.
416 /// [`&str`]: ../../std/primitive.str.html
417 /// [`u8`]: ../../std/primitive.u8.html
418 /// [`Vec<u8>`]: ../../std/vec/struct.Vec.html
420 /// If you are sure that the byte slice is valid UTF-8, and you don't want
421 /// to incur the overhead of the validity check, there is an unsafe version
422 /// of this function, [`from_utf8_unchecked()`], which has the same behavior
423 /// but skips the check.
425 /// [`from_utf8_unchecked()`]: struct.String.html#method.from_utf8_unchecked
427 /// This method will take care to not copy the vector, for efficiency's
430 /// If you need a `&str` instead of a `String`, consider
431 /// [`str::from_utf8()`].
433 /// [`str::from_utf8()`]: ../../std/str/fn.from_utf8.html
437 /// Returns `Err` if the slice is not UTF-8 with a description as to why the
438 /// provided bytes are not UTF-8. The vector you moved in is also included.
445 /// // some bytes, in a vector
446 /// let sparkle_heart = vec![240, 159, 146, 150];
448 /// // We know these bytes are valid, so we'll use `unwrap()`.
449 /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
451 /// assert_eq!("💖", sparkle_heart);
457 /// // some invalid bytes, in a vector
458 /// let sparkle_heart = vec![0, 159, 146, 150];
460 /// assert!(String::from_utf8(sparkle_heart).is_err());
463 /// See the docs for [`FromUtf8Error`] for more details on what you can do
466 /// [`FromUtf8Error`]: struct.FromUtf8Error.html
468 #[stable(feature = "rust1", since = "1.0.0")]
469 pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error> {
470 match str::from_utf8(&vec) {
471 Ok(..) => Ok(String { vec: vec }),
481 /// Converts a slice of bytes to a string, including invalid characters.
483 /// Strings are made of bytes ([`u8`]), and a slice of bytes
484 /// ([`&[u8]`][byteslice]) is made of bytes, so this function converts
485 /// between the two. Not all byte slices are valid strings, however: strings
486 /// are required to be valid UTF-8. During this conversion,
487 /// `from_utf8_lossy()` will replace any invalid UTF-8 sequences with
488 /// `U+FFFD REPLACEMENT CHARACTER`, which looks like this: �
490 /// [`u8`]: ../../std/primitive.u8.html
491 /// [byteslice]: ../../std/primitive.slice.html
493 /// If you are sure that the byte slice is valid UTF-8, and you don't want
494 /// to incur the overhead of the conversion, there is an unsafe version
495 /// of this function, [`from_utf8_unchecked()`], which has the same behavior
496 /// but skips the checks.
498 /// [`from_utf8_unchecked()`]: struct.String.html#method.from_utf8_unchecked
500 /// This function returns a [`Cow<'a, str>`]. If our byte slice is invalid
501 /// UTF-8, then we need to insert the replacement characters, which will
502 /// change the size of the string, and hence, require a `String`. But if
503 /// it's already valid UTF-8, we don't need a new allocation. This return
504 /// type allows us to handle both cases.
506 /// [`Cow<'a, str>`]: ../../std/borrow/enum.Cow.html
513 /// // some bytes, in a vector
514 /// let sparkle_heart = vec![240, 159, 146, 150];
516 /// let sparkle_heart = String::from_utf8_lossy(&sparkle_heart);
518 /// assert_eq!("💖", sparkle_heart);
524 /// // some invalid bytes
525 /// let input = b"Hello \xF0\x90\x80World";
526 /// let output = String::from_utf8_lossy(input);
528 /// assert_eq!("Hello �World", output);
530 #[stable(feature = "rust1", since = "1.0.0")]
531 pub fn from_utf8_lossy<'a>(v: &'a [u8]) -> Cow<'a, str> {
533 match str::from_utf8(v) {
534 Ok(s) => return Cow::Borrowed(s),
535 Err(e) => i = e.valid_up_to(),
538 const TAG_CONT_U8: u8 = 128;
539 const REPLACEMENT: &'static [u8] = b"\xEF\xBF\xBD"; // U+FFFD in UTF-8
541 fn unsafe_get(xs: &[u8], i: usize) -> u8 {
542 unsafe { *xs.get_unchecked(i) }
544 fn safe_get(xs: &[u8], i: usize, total: usize) -> u8 {
552 let mut res = String::with_capacity(total);
555 unsafe { res.as_mut_vec().extend_from_slice(&v[..i]) };
558 // subseqidx is the index of the first byte of the subsequence we're
559 // looking at. It's used to copy a bunch of contiguous good codepoints
560 // at once instead of copying them one by one.
561 let mut subseqidx = i;
565 let byte = unsafe_get(v, i);
568 macro_rules! error { () => ({
571 res.as_mut_vec().extend_from_slice(&v[subseqidx..i_]);
574 res.as_mut_vec().extend_from_slice(REPLACEMENT);
579 // subseqidx handles this
581 let w = unicode_str::utf8_char_width(byte);
585 if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
592 match (byte, safe_get(v, i, total)) {
593 (0xE0, 0xA0...0xBF) => (),
594 (0xE1...0xEC, 0x80...0xBF) => (),
595 (0xED, 0x80...0x9F) => (),
596 (0xEE...0xEF, 0x80...0xBF) => (),
603 if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
610 match (byte, safe_get(v, i, total)) {
611 (0xF0, 0x90...0xBF) => (),
612 (0xF1...0xF3, 0x80...0xBF) => (),
613 (0xF4, 0x80...0x8F) => (),
620 if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
625 if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
638 if subseqidx < total {
639 unsafe { res.as_mut_vec().extend_from_slice(&v[subseqidx..total]) };
644 /// Decode a UTF-16 encoded vector `v` into a `String`, returning `Err`
645 /// if `v` contains any invalid data.
653 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
654 /// 0x0073, 0x0069, 0x0063];
655 /// assert_eq!(String::from("𝄞music"),
656 /// String::from_utf16(v).unwrap());
658 /// // 𝄞mu<invalid>ic
659 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
660 /// 0xD800, 0x0069, 0x0063];
661 /// assert!(String::from_utf16(v).is_err());
663 #[stable(feature = "rust1", since = "1.0.0")]
664 pub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error> {
665 decode_utf16(v.iter().cloned()).collect::<Result<_, _>>().map_err(|_| FromUtf16Error(()))
668 /// Decode a UTF-16 encoded vector `v` into a string, replacing
669 /// invalid data with the replacement character (U+FFFD).
676 /// // 𝄞mus<invalid>ic<invalid>
677 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
678 /// 0x0073, 0xDD1E, 0x0069, 0x0063,
681 /// assert_eq!(String::from("𝄞mus\u{FFFD}ic\u{FFFD}"),
682 /// String::from_utf16_lossy(v));
685 #[stable(feature = "rust1", since = "1.0.0")]
686 pub fn from_utf16_lossy(v: &[u16]) -> String {
687 decode_utf16(v.iter().cloned()).map(|r| r.unwrap_or(REPLACEMENT_CHARACTER)).collect()
690 /// Creates a new `String` from a length, capacity, and pointer.
694 /// This is highly unsafe, due to the number of invariants that aren't
697 /// * The memory at `ptr` needs to have been previously allocated by the
698 /// same allocator the standard library uses.
699 /// * `length` needs to be less than or equal to `capacity`.
700 /// * `capacity` needs to be the correct value.
702 /// Violating these may cause problems like corrupting the allocator's
703 /// internal datastructures.
705 /// The ownership of `ptr` is effectively transferred to the
706 /// `String` which may then deallocate, reallocate or change the
707 /// contents of memory pointed to by the pointer at will. Ensure
708 /// that nothing else uses the pointer after calling this
719 /// let s = String::from("hello");
720 /// let ptr = s.as_ptr();
721 /// let len = s.len();
722 /// let capacity = s.capacity();
726 /// let s = String::from_raw_parts(ptr as *mut _, len, capacity);
728 /// assert_eq!(String::from("hello"), s);
732 #[stable(feature = "rust1", since = "1.0.0")]
733 pub unsafe fn from_raw_parts(buf: *mut u8, length: usize, capacity: usize) -> String {
734 String { vec: Vec::from_raw_parts(buf, length, capacity) }
737 /// Converts a vector of bytes to a `String` without checking that the
738 /// string contains valid UTF-8.
740 /// See the safe version, [`from_utf8()`], for more details.
742 /// [`from_utf8()`]: struct.String.html#method.from_utf8
746 /// This function is unsafe because it does not check that the bytes passed
747 /// to it are valid UTF-8. If this constraint is violated, it may cause
748 /// memory unsafety issues with future users of the `String`, as the rest of
749 /// the standard library assumes that `String`s are valid UTF-8.
756 /// // some bytes, in a vector
757 /// let sparkle_heart = vec![240, 159, 146, 150];
759 /// let sparkle_heart = unsafe {
760 /// String::from_utf8_unchecked(sparkle_heart)
763 /// assert_eq!("💖", sparkle_heart);
766 #[stable(feature = "rust1", since = "1.0.0")]
767 pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String {
768 String { vec: bytes }
771 /// Converts a `String` into a byte vector.
773 /// This consumes the `String`, so we do not need to copy its contents.
780 /// let s = String::from("hello");
781 /// let bytes = s.into_bytes();
783 /// assert_eq!(&[104, 101, 108, 108, 111][..], &bytes[..]);
786 #[stable(feature = "rust1", since = "1.0.0")]
787 pub fn into_bytes(self) -> Vec<u8> {
791 /// Extracts a string slice containing the entire string.
793 #[stable(feature = "string_as_str", since = "1.7.0")]
794 pub fn as_str(&self) -> &str {
798 /// Extracts a string slice containing the entire string.
800 #[stable(feature = "string_as_str", since = "1.7.0")]
801 pub fn as_mut_str(&mut self) -> &mut str {
805 /// Appends a given string slice onto the end of this `String`.
812 /// let mut s = String::from("foo");
814 /// s.push_str("bar");
816 /// assert_eq!("foobar", s);
819 #[stable(feature = "rust1", since = "1.0.0")]
820 pub fn push_str(&mut self, string: &str) {
821 self.vec.extend_from_slice(string.as_bytes())
824 /// Returns this `String`'s capacity, in bytes.
831 /// let s = String::with_capacity(10);
833 /// assert!(s.capacity() >= 10);
836 #[stable(feature = "rust1", since = "1.0.0")]
837 pub fn capacity(&self) -> usize {
841 /// Ensures that this `String`'s capacity is at least `additional` bytes
842 /// larger than its length.
844 /// The capacity may be increased by more than `additional` bytes if it
845 /// chooses, to prevent frequent reallocations.
847 /// If you do not want this "at least" behavior, see the [`reserve_exact()`]
850 /// [`reserve_exact()`]: #method.reserve_exact
854 /// Panics if the new capacity overflows `usize`.
861 /// let mut s = String::new();
865 /// assert!(s.capacity() >= 10);
868 /// This may not actually increase the capacity:
871 /// let mut s = String::with_capacity(10);
875 /// // s now has a length of 2 and a capacity of 10
876 /// assert_eq!(2, s.len());
877 /// assert_eq!(10, s.capacity());
879 /// // Since we already have an extra 8 capacity, calling this...
882 /// // ... doesn't actually increase.
883 /// assert_eq!(10, s.capacity());
886 #[stable(feature = "rust1", since = "1.0.0")]
887 pub fn reserve(&mut self, additional: usize) {
888 self.vec.reserve(additional)
891 /// Ensures that this `String`'s capacity is `additional` bytes
892 /// larger than its length.
894 /// Consider using the [`reserve()`] method unless you absolutely know
895 /// better than the allocator.
897 /// [`reserve()`]: #method.reserve
901 /// Panics if the new capacity overflows `usize`.
908 /// let mut s = String::new();
910 /// s.reserve_exact(10);
912 /// assert!(s.capacity() >= 10);
915 /// This may not actually increase the capacity:
918 /// let mut s = String::with_capacity(10);
922 /// // s now has a length of 2 and a capacity of 10
923 /// assert_eq!(2, s.len());
924 /// assert_eq!(10, s.capacity());
926 /// // Since we already have an extra 8 capacity, calling this...
927 /// s.reserve_exact(8);
929 /// // ... doesn't actually increase.
930 /// assert_eq!(10, s.capacity());
933 #[stable(feature = "rust1", since = "1.0.0")]
934 pub fn reserve_exact(&mut self, additional: usize) {
935 self.vec.reserve_exact(additional)
938 /// Shrinks the capacity of this `String` to match its length.
945 /// let mut s = String::from("foo");
948 /// assert!(s.capacity() >= 100);
950 /// s.shrink_to_fit();
951 /// assert_eq!(3, s.capacity());
954 #[stable(feature = "rust1", since = "1.0.0")]
955 pub fn shrink_to_fit(&mut self) {
956 self.vec.shrink_to_fit()
959 /// Appends the given `char` to the end of this `String`.
966 /// let mut s = String::from("abc");
972 /// assert_eq!("abc123", s);
975 #[stable(feature = "rust1", since = "1.0.0")]
976 pub fn push(&mut self, ch: char) {
977 match ch.len_utf8() {
978 1 => self.vec.push(ch as u8),
979 _ => self.vec.extend_from_slice(ch.encode_utf8(&mut [0;4]).as_bytes()),
983 /// Returns a byte slice of this `String`'s contents.
990 /// let s = String::from("hello");
992 /// assert_eq!(&[104, 101, 108, 108, 111], s.as_bytes());
995 #[stable(feature = "rust1", since = "1.0.0")]
996 pub fn as_bytes(&self) -> &[u8] {
1000 /// Shortens this `String` to the specified length.
1002 /// If `new_len` is greater than the string's current length, this has no
1007 /// Panics if `new_len` does not lie on a [`char`] boundary.
1009 /// [`char`]: ../../std/primitive.char.html
1016 /// let mut s = String::from("hello");
1020 /// assert_eq!("he", s);
1023 #[stable(feature = "rust1", since = "1.0.0")]
1024 pub fn truncate(&mut self, new_len: usize) {
1025 if new_len <= self.len() {
1026 assert!(self.is_char_boundary(new_len));
1027 self.vec.truncate(new_len)
1031 /// Removes the last character from the string buffer and returns it.
1033 /// Returns `None` if this `String` is empty.
1040 /// let mut s = String::from("foo");
1042 /// assert_eq!(s.pop(), Some('o'));
1043 /// assert_eq!(s.pop(), Some('o'));
1044 /// assert_eq!(s.pop(), Some('f'));
1046 /// assert_eq!(s.pop(), None);
1049 #[stable(feature = "rust1", since = "1.0.0")]
1050 pub fn pop(&mut self) -> Option<char> {
1051 let ch = match self.chars().rev().next() {
1053 None => return None,
1055 let newlen = self.len() - ch.len_utf8();
1057 self.vec.set_len(newlen);
1062 /// Removes a `char` from this `String` at a byte position and returns it.
1064 /// This is an `O(n)` operation, as it requires copying every element in the
1069 /// Panics if `idx` is larger than or equal to the `String`'s length,
1070 /// or if it does not lie on a [`char`] boundary.
1072 /// [`char`]: ../../std/primitive.char.html
1079 /// let mut s = String::from("foo");
1081 /// assert_eq!(s.remove(0), 'f');
1082 /// assert_eq!(s.remove(1), 'o');
1083 /// assert_eq!(s.remove(0), 'o');
1086 #[stable(feature = "rust1", since = "1.0.0")]
1087 pub fn remove(&mut self, idx: usize) -> char {
1088 let ch = match self[idx..].chars().next() {
1090 None => panic!("cannot remove a char from the end of a string"),
1093 let next = idx + ch.len_utf8();
1094 let len = self.len();
1096 ptr::copy(self.vec.as_ptr().offset(next as isize),
1097 self.vec.as_mut_ptr().offset(idx as isize),
1099 self.vec.set_len(len - (next - idx));
1104 /// Inserts a character into this `String` at a byte position.
1106 /// This is an `O(n)` operation as it requires copying every element in the
1111 /// Panics if `idx` is larger than the `String`'s length, or if it does not
1112 /// lie on a [`char`] boundary.
1114 /// [`char`]: ../../std/primitive.char.html
1121 /// let mut s = String::with_capacity(3);
1123 /// s.insert(0, 'f');
1124 /// s.insert(1, 'o');
1125 /// s.insert(2, 'o');
1127 /// assert_eq!("foo", s);
1130 #[stable(feature = "rust1", since = "1.0.0")]
1131 pub fn insert(&mut self, idx: usize, ch: char) {
1132 assert!(self.is_char_boundary(idx));
1133 let mut bits = [0; 4];
1134 let bits = ch.encode_utf8(&mut bits).as_bytes();
1137 self.insert_bytes(idx, bits);
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 assert!(self.is_char_boundary(idx));
1188 self.insert_bytes(idx, string.as_bytes());
1192 /// Returns a mutable reference to the contents of this `String`.
1196 /// This function is unsafe because it does not check that the bytes passed
1197 /// to it are valid UTF-8. If this constraint is violated, it may cause
1198 /// memory unsafety issues with future users of the `String`, as the rest of
1199 /// the standard library assumes that `String`s are valid UTF-8.
1206 /// let mut s = String::from("hello");
1209 /// let vec = s.as_mut_vec();
1210 /// assert_eq!(&[104, 101, 108, 108, 111][..], &vec[..]);
1214 /// assert_eq!(s, "olleh");
1217 #[stable(feature = "rust1", since = "1.0.0")]
1218 pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1222 /// Returns the length of this `String`, in bytes.
1229 /// let a = String::from("foo");
1231 /// assert_eq!(a.len(), 3);
1234 #[stable(feature = "rust1", since = "1.0.0")]
1235 pub fn len(&self) -> usize {
1239 /// Returns `true` if this `String` has a length of zero.
1241 /// Returns `false` otherwise.
1248 /// let mut v = String::new();
1249 /// assert!(v.is_empty());
1252 /// assert!(!v.is_empty());
1255 #[stable(feature = "rust1", since = "1.0.0")]
1256 pub fn is_empty(&self) -> bool {
1260 /// Divide one string into two at an index.
1262 /// The argument, `mid`, should be a byte offset from the start of the string. It must also
1263 /// be on the boundary of a UTF-8 code point.
1265 /// The two strings returned go from the start of the string to `mid`, and from `mid` to the end
1270 /// Panics if `mid` is not on a `UTF-8` code point boundary, or if it is beyond the last
1271 /// code point of the string.
1276 /// # #![feature(string_split_off)]
1278 /// let mut hello = String::from("Hello, World!");
1279 /// let world = hello.split_off(7);
1280 /// assert_eq!(hello, "Hello, ");
1281 /// assert_eq!(world, "World!");
1285 #[unstable(feature = "string_split_off", issue = "38080")]
1286 pub fn split_off(&mut self, mid: usize) -> String {
1287 assert!(self.is_char_boundary(mid));
1288 let other = self.vec.split_off(mid);
1289 unsafe { String::from_utf8_unchecked(other) }
1292 /// Truncates this `String`, removing all contents.
1294 /// While this means the `String` will have a length of zero, it does not
1295 /// touch its capacity.
1302 /// let mut s = String::from("foo");
1306 /// assert!(s.is_empty());
1307 /// assert_eq!(0, s.len());
1308 /// assert_eq!(3, s.capacity());
1311 #[stable(feature = "rust1", since = "1.0.0")]
1312 pub fn clear(&mut self) {
1316 /// Create a draining iterator that removes the specified range in the string
1317 /// and yields the removed chars.
1319 /// Note: The element range is removed even if the iterator is not
1320 /// consumed until the end.
1324 /// Panics if the starting point or end point do not lie on a [`char`]
1325 /// boundary, or if they're out of bounds.
1327 /// [`char`]: ../../std/primitive.char.html
1334 /// let mut s = String::from("α is alpha, β is beta");
1335 /// let beta_offset = s.find('β').unwrap_or(s.len());
1337 /// // Remove the range up until the β from the string
1338 /// let t: String = s.drain(..beta_offset).collect();
1339 /// assert_eq!(t, "α is alpha, ");
1340 /// assert_eq!(s, "β is beta");
1342 /// // A full range clears the string
1344 /// assert_eq!(s, "");
1346 #[stable(feature = "drain", since = "1.6.0")]
1347 pub fn drain<R>(&mut self, range: R) -> Drain
1348 where R: RangeArgument<usize>
1352 // The String version of Drain does not have the memory safety issues
1353 // of the vector version. The data is just plain bytes.
1354 // Because the range removal happens in Drop, if the Drain iterator is leaked,
1355 // the removal will not happen.
1356 let len = self.len();
1357 let start = *range.start().unwrap_or(&0);
1358 let end = *range.end().unwrap_or(&len);
1360 // Take out two simultaneous borrows. The &mut String won't be accessed
1361 // until iteration is over, in Drop.
1362 let self_ptr = self as *mut _;
1363 // slicing does the appropriate bounds checks
1364 let chars_iter = self[start..end].chars();
1374 /// Converts this `String` into a `Box<str>`.
1376 /// This will drop any excess capacity.
1383 /// let s = String::from("hello");
1385 /// let b = s.into_boxed_str();
1387 #[stable(feature = "box_str", since = "1.4.0")]
1388 pub fn into_boxed_str(self) -> Box<str> {
1389 let slice = self.vec.into_boxed_slice();
1390 unsafe { mem::transmute::<Box<[u8]>, Box<str>>(slice) }
1394 impl FromUtf8Error {
1395 /// Returns the bytes that were attempted to convert to a `String`.
1397 /// This method is carefully constructed to avoid allocation. It will
1398 /// consume the error, moving out the bytes, so that a copy of the bytes
1399 /// does not need to be made.
1406 /// // some invalid bytes, in a vector
1407 /// let bytes = vec![0, 159];
1409 /// let value = String::from_utf8(bytes);
1411 /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
1413 #[stable(feature = "rust1", since = "1.0.0")]
1414 pub fn into_bytes(self) -> Vec<u8> {
1418 /// Fetch a `Utf8Error` to get more details about the conversion failure.
1420 /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
1421 /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
1422 /// an analogue to `FromUtf8Error`. See its documentation for more details
1425 /// [`Utf8Error`]: ../../std/str/struct.Utf8Error.html
1426 /// [`std::str`]: ../../std/str/index.html
1427 /// [`u8`]: ../../std/primitive.u8.html
1428 /// [`&str`]: ../../std/primitive.str.html
1435 /// // some invalid bytes, in a vector
1436 /// let bytes = vec![0, 159];
1438 /// let error = String::from_utf8(bytes).unwrap_err().utf8_error();
1440 /// // the first byte is invalid here
1441 /// assert_eq!(1, error.valid_up_to());
1443 #[stable(feature = "rust1", since = "1.0.0")]
1444 pub fn utf8_error(&self) -> Utf8Error {
1449 #[stable(feature = "rust1", since = "1.0.0")]
1450 impl fmt::Display for FromUtf8Error {
1451 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1452 fmt::Display::fmt(&self.error, f)
1456 #[stable(feature = "rust1", since = "1.0.0")]
1457 impl fmt::Display for FromUtf16Error {
1458 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1459 fmt::Display::fmt("invalid utf-16: lone surrogate found", f)
1463 #[stable(feature = "rust1", since = "1.0.0")]
1464 impl Clone for String {
1465 fn clone(&self) -> Self {
1466 String { vec: self.vec.clone() }
1469 fn clone_from(&mut self, source: &Self) {
1470 self.vec.clone_from(&source.vec);
1474 #[stable(feature = "rust1", since = "1.0.0")]
1475 impl FromIterator<char> for String {
1476 fn from_iter<I: IntoIterator<Item = char>>(iter: I) -> String {
1477 let mut buf = String::new();
1483 #[stable(feature = "rust1", since = "1.0.0")]
1484 impl<'a> FromIterator<&'a str> for String {
1485 fn from_iter<I: IntoIterator<Item = &'a str>>(iter: I) -> String {
1486 let mut buf = String::new();
1492 #[stable(feature = "extend_string", since = "1.4.0")]
1493 impl FromIterator<String> for String {
1494 fn from_iter<I: IntoIterator<Item = String>>(iter: I) -> String {
1495 let mut buf = String::new();
1501 #[stable(feature = "rust1", since = "1.0.0")]
1502 impl Extend<char> for String {
1503 fn extend<I: IntoIterator<Item = char>>(&mut self, iter: I) {
1504 let iterator = iter.into_iter();
1505 let (lower_bound, _) = iterator.size_hint();
1506 self.reserve(lower_bound);
1507 for ch in iterator {
1513 #[stable(feature = "extend_ref", since = "1.2.0")]
1514 impl<'a> Extend<&'a char> for String {
1515 fn extend<I: IntoIterator<Item = &'a char>>(&mut self, iter: I) {
1516 self.extend(iter.into_iter().cloned());
1520 #[stable(feature = "rust1", since = "1.0.0")]
1521 impl<'a> Extend<&'a str> for String {
1522 fn extend<I: IntoIterator<Item = &'a str>>(&mut self, iter: I) {
1529 #[stable(feature = "extend_string", since = "1.4.0")]
1530 impl Extend<String> for String {
1531 fn extend<I: IntoIterator<Item = String>>(&mut self, iter: I) {
1538 /// A convenience impl that delegates to the impl for `&str`
1539 #[unstable(feature = "pattern",
1540 reason = "API not fully fleshed out and ready to be stabilized",
1542 impl<'a, 'b> Pattern<'a> for &'b String {
1543 type Searcher = <&'b str as Pattern<'a>>::Searcher;
1545 fn into_searcher(self, haystack: &'a str) -> <&'b str as Pattern<'a>>::Searcher {
1546 self[..].into_searcher(haystack)
1550 fn is_contained_in(self, haystack: &'a str) -> bool {
1551 self[..].is_contained_in(haystack)
1555 fn is_prefix_of(self, haystack: &'a str) -> bool {
1556 self[..].is_prefix_of(haystack)
1560 #[stable(feature = "rust1", since = "1.0.0")]
1561 impl PartialEq for String {
1563 fn eq(&self, other: &String) -> bool {
1564 PartialEq::eq(&self[..], &other[..])
1567 fn ne(&self, other: &String) -> bool {
1568 PartialEq::ne(&self[..], &other[..])
1572 macro_rules! impl_eq {
1573 ($lhs:ty, $rhs: ty) => {
1574 #[stable(feature = "rust1", since = "1.0.0")]
1575 impl<'a, 'b> PartialEq<$rhs> for $lhs {
1577 fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
1579 fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
1582 #[stable(feature = "rust1", since = "1.0.0")]
1583 impl<'a, 'b> PartialEq<$lhs> for $rhs {
1585 fn eq(&self, other: &$lhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
1587 fn ne(&self, other: &$lhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
1593 impl_eq! { String, str }
1594 impl_eq! { String, &'a str }
1595 impl_eq! { Cow<'a, str>, str }
1596 impl_eq! { Cow<'a, str>, &'b str }
1597 impl_eq! { Cow<'a, str>, String }
1599 #[stable(feature = "rust1", since = "1.0.0")]
1600 impl Default for String {
1601 /// Creates an empty `String`.
1603 fn default() -> String {
1608 #[stable(feature = "rust1", since = "1.0.0")]
1609 impl fmt::Display for String {
1611 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1612 fmt::Display::fmt(&**self, f)
1616 #[stable(feature = "rust1", since = "1.0.0")]
1617 impl fmt::Debug for String {
1619 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1620 fmt::Debug::fmt(&**self, f)
1624 #[stable(feature = "rust1", since = "1.0.0")]
1625 impl hash::Hash for String {
1627 fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
1628 (**self).hash(hasher)
1632 #[stable(feature = "rust1", since = "1.0.0")]
1633 impl<'a> Add<&'a str> for String {
1634 type Output = String;
1637 fn add(mut self, other: &str) -> String {
1638 self.push_str(other);
1643 #[stable(feature = "stringaddassign", since = "1.12.0")]
1644 impl<'a> AddAssign<&'a str> for String {
1646 fn add_assign(&mut self, other: &str) {
1647 self.push_str(other);
1651 #[stable(feature = "rust1", since = "1.0.0")]
1652 impl ops::Index<ops::Range<usize>> for String {
1656 fn index(&self, index: ops::Range<usize>) -> &str {
1660 #[stable(feature = "rust1", since = "1.0.0")]
1661 impl ops::Index<ops::RangeTo<usize>> for String {
1665 fn index(&self, index: ops::RangeTo<usize>) -> &str {
1669 #[stable(feature = "rust1", since = "1.0.0")]
1670 impl ops::Index<ops::RangeFrom<usize>> for String {
1674 fn index(&self, index: ops::RangeFrom<usize>) -> &str {
1678 #[stable(feature = "rust1", since = "1.0.0")]
1679 impl ops::Index<ops::RangeFull> for String {
1683 fn index(&self, _index: ops::RangeFull) -> &str {
1684 unsafe { str::from_utf8_unchecked(&self.vec) }
1687 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1688 impl ops::Index<ops::RangeInclusive<usize>> for String {
1692 fn index(&self, index: ops::RangeInclusive<usize>) -> &str {
1693 Index::index(&**self, index)
1696 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1697 impl ops::Index<ops::RangeToInclusive<usize>> for String {
1701 fn index(&self, index: ops::RangeToInclusive<usize>) -> &str {
1702 Index::index(&**self, index)
1706 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1707 impl ops::IndexMut<ops::Range<usize>> for String {
1709 fn index_mut(&mut self, index: ops::Range<usize>) -> &mut str {
1710 &mut self[..][index]
1713 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1714 impl ops::IndexMut<ops::RangeTo<usize>> for String {
1716 fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut str {
1717 &mut self[..][index]
1720 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1721 impl ops::IndexMut<ops::RangeFrom<usize>> for String {
1723 fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut str {
1724 &mut self[..][index]
1727 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1728 impl ops::IndexMut<ops::RangeFull> for String {
1730 fn index_mut(&mut self, _index: ops::RangeFull) -> &mut str {
1731 unsafe { mem::transmute(&mut *self.vec) }
1734 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1735 impl ops::IndexMut<ops::RangeInclusive<usize>> for String {
1737 fn index_mut(&mut self, index: ops::RangeInclusive<usize>) -> &mut str {
1738 IndexMut::index_mut(&mut **self, index)
1741 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1742 impl ops::IndexMut<ops::RangeToInclusive<usize>> for String {
1744 fn index_mut(&mut self, index: ops::RangeToInclusive<usize>) -> &mut str {
1745 IndexMut::index_mut(&mut **self, index)
1749 #[stable(feature = "rust1", since = "1.0.0")]
1750 impl ops::Deref for String {
1754 fn deref(&self) -> &str {
1755 unsafe { str::from_utf8_unchecked(&self.vec) }
1759 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1760 impl ops::DerefMut for String {
1762 fn deref_mut(&mut self) -> &mut str {
1763 unsafe { mem::transmute(&mut *self.vec) }
1767 /// An error when parsing a `String`.
1769 /// This `enum` is slightly awkward: it will never actually exist. This error is
1770 /// part of the type signature of the implementation of [`FromStr`] on
1771 /// [`String`]. The return type of [`from_str()`], requires that an error be
1772 /// defined, but, given that a [`String`] can always be made into a new
1773 /// [`String`] without error, this type will never actually be returned. As
1774 /// such, it is only here to satisfy said signature, and is useless otherwise.
1776 /// [`FromStr`]: ../../std/str/trait.FromStr.html
1777 /// [`String`]: struct.String.html
1778 /// [`from_str()`]: ../../std/str/trait.FromStr.html#tymethod.from_str
1779 #[stable(feature = "str_parse_error", since = "1.5.0")]
1781 pub enum ParseError {}
1783 #[stable(feature = "rust1", since = "1.0.0")]
1784 impl FromStr for String {
1785 type Err = ParseError;
1787 fn from_str(s: &str) -> Result<String, ParseError> {
1792 #[stable(feature = "str_parse_error", since = "1.5.0")]
1793 impl Clone for ParseError {
1794 fn clone(&self) -> ParseError {
1799 #[stable(feature = "str_parse_error", since = "1.5.0")]
1800 impl fmt::Debug for ParseError {
1801 fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result {
1806 #[stable(feature = "str_parse_error2", since = "1.8.0")]
1807 impl fmt::Display for ParseError {
1808 fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result {
1813 #[stable(feature = "str_parse_error", since = "1.5.0")]
1814 impl PartialEq for ParseError {
1815 fn eq(&self, _: &ParseError) -> bool {
1820 #[stable(feature = "str_parse_error", since = "1.5.0")]
1821 impl Eq for ParseError {}
1823 /// A trait for converting a value to a `String`.
1825 /// This trait is automatically implemented for any type which implements the
1826 /// [`Display`] trait. As such, `ToString` shouldn't be implemented directly:
1827 /// [`Display`] should be implemented instead, and you get the `ToString`
1828 /// implementation for free.
1830 /// [`Display`]: ../../std/fmt/trait.Display.html
1831 #[stable(feature = "rust1", since = "1.0.0")]
1832 pub trait ToString {
1833 /// Converts the given value to a `String`.
1841 /// let five = String::from("5");
1843 /// assert_eq!(five, i.to_string());
1845 #[stable(feature = "rust1", since = "1.0.0")]
1846 fn to_string(&self) -> String;
1849 #[stable(feature = "rust1", since = "1.0.0")]
1850 impl<T: fmt::Display + ?Sized> ToString for T {
1852 default fn to_string(&self) -> String {
1853 use core::fmt::Write;
1854 let mut buf = String::new();
1855 let _ = buf.write_fmt(format_args!("{}", self));
1856 buf.shrink_to_fit();
1861 #[stable(feature = "str_to_string_specialization", since = "1.9.0")]
1862 impl ToString for str {
1864 fn to_string(&self) -> String {
1869 #[stable(feature = "rust1", since = "1.0.0")]
1870 impl AsRef<str> for String {
1872 fn as_ref(&self) -> &str {
1877 #[stable(feature = "rust1", since = "1.0.0")]
1878 impl AsRef<[u8]> for String {
1880 fn as_ref(&self) -> &[u8] {
1885 #[stable(feature = "rust1", since = "1.0.0")]
1886 impl<'a> From<&'a str> for String {
1887 fn from(s: &'a str) -> String {
1892 #[stable(feature = "string_from_cow_str", since = "1.14.0")]
1893 impl<'a> From<Cow<'a, str>> for String {
1894 fn from(s: Cow<'a, str>) -> String {
1899 #[stable(feature = "rust1", since = "1.0.0")]
1900 impl<'a> From<&'a str> for Cow<'a, str> {
1902 fn from(s: &'a str) -> Cow<'a, str> {
1907 #[stable(feature = "rust1", since = "1.0.0")]
1908 impl<'a> From<String> for Cow<'a, str> {
1910 fn from(s: String) -> Cow<'a, str> {
1915 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
1916 impl<'a> FromIterator<char> for Cow<'a, str> {
1917 fn from_iter<I: IntoIterator<Item = char>>(it: I) -> Cow<'a, str> {
1918 Cow::Owned(FromIterator::from_iter(it))
1922 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
1923 impl<'a, 'b> FromIterator<&'b str> for Cow<'a, str> {
1924 fn from_iter<I: IntoIterator<Item = &'b str>>(it: I) -> Cow<'a, str> {
1925 Cow::Owned(FromIterator::from_iter(it))
1929 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
1930 impl<'a> FromIterator<String> for Cow<'a, str> {
1931 fn from_iter<I: IntoIterator<Item = String>>(it: I) -> Cow<'a, str> {
1932 Cow::Owned(FromIterator::from_iter(it))
1936 #[stable(feature = "from_string_for_vec_u8", since = "1.14.0")]
1937 impl From<String> for Vec<u8> {
1938 fn from(string : String) -> Vec<u8> {
1943 #[stable(feature = "rust1", since = "1.0.0")]
1944 impl fmt::Write for String {
1946 fn write_str(&mut self, s: &str) -> fmt::Result {
1952 fn write_char(&mut self, c: char) -> fmt::Result {
1958 /// A draining iterator for `String`.
1960 /// This struct is created by the [`drain()`] method on [`String`]. See its
1961 /// documentation for more.
1963 /// [`drain()`]: struct.String.html#method.drain
1964 /// [`String`]: struct.String.html
1965 #[stable(feature = "drain", since = "1.6.0")]
1966 pub struct Drain<'a> {
1967 /// Will be used as &'a mut String in the destructor
1968 string: *mut String,
1969 /// Start of part to remove
1971 /// End of part to remove
1973 /// Current remaining range to remove
1977 #[stable(feature = "drain", since = "1.6.0")]
1978 unsafe impl<'a> Sync for Drain<'a> {}
1979 #[stable(feature = "drain", since = "1.6.0")]
1980 unsafe impl<'a> Send for Drain<'a> {}
1982 #[stable(feature = "drain", since = "1.6.0")]
1983 impl<'a> Drop for Drain<'a> {
1984 fn drop(&mut self) {
1986 // Use Vec::drain. "Reaffirm" the bounds checks to avoid
1987 // panic code being inserted again.
1988 let self_vec = (*self.string).as_mut_vec();
1989 if self.start <= self.end && self.end <= self_vec.len() {
1990 self_vec.drain(self.start..self.end);
1996 #[stable(feature = "drain", since = "1.6.0")]
1997 impl<'a> Iterator for Drain<'a> {
2001 fn next(&mut self) -> Option<char> {
2005 fn size_hint(&self) -> (usize, Option<usize>) {
2006 self.iter.size_hint()
2010 #[stable(feature = "drain", since = "1.6.0")]
2011 impl<'a> DoubleEndedIterator for Drain<'a> {
2013 fn next_back(&mut self) -> Option<char> {
2014 self.iter.next_back()
2018 #[unstable(feature = "fused", issue = "35602")]
2019 impl<'a> FusedIterator for Drain<'a> {}