1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! A UTF-8 encoded, growable string.
13 //! This module contains the [`String`] type, a trait for converting
14 //! [`ToString`]s, and several error types that may result from working with
17 //! [`ToString`]: trait.ToString.html
21 //! There are multiple ways to create a new [`String`] from a string literal:
24 //! let s = "Hello".to_string();
26 //! let s = String::from("world");
27 //! let s: String = "also this".into();
30 //! You can create a new [`String`] from an existing one by concatenating with
33 //! [`String`]: struct.String.html
36 //! let s = "Hello".to_string();
38 //! let message = s + " world!";
41 //! If you have a vector of valid UTF-8 bytes, you can make a `String` out of
42 //! it. You can do the reverse too.
45 //! let sparkle_heart = vec![240, 159, 146, 150];
47 //! // We know these bytes are valid, so we'll use `unwrap()`.
48 //! let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
50 //! assert_eq!("💖", sparkle_heart);
52 //! let bytes = sparkle_heart.into_bytes();
54 //! assert_eq!(bytes, [240, 159, 146, 150]);
57 #![stable(feature = "rust1", since = "1.0.0")]
59 use alloc::str as alloc_str;
63 use core::iter::{FromIterator, FusedIterator};
64 use core::ops::{self, Add, AddAssign, Index, IndexMut};
66 use core::str as core_str;
67 use core::str::pattern::Pattern;
68 use std_unicode::char::{decode_utf16, REPLACEMENT_CHARACTER};
70 use borrow::{Cow, ToOwned};
71 use range::RangeArgument;
72 use Bound::{Excluded, Included, Unbounded};
73 use str::{self, FromStr, Utf8Error, Chars};
77 /// A UTF-8 encoded, growable string.
79 /// The `String` type is the most common string type that has ownership over the
80 /// contents of the string. It has a close relationship with its borrowed
81 /// counterpart, the primitive [`str`].
83 /// [`str`]: ../../std/primitive.str.html
87 /// You can create a `String` from a literal string with `String::from`:
90 /// let hello = String::from("Hello, world!");
93 /// You can append a [`char`] to a `String` with the [`push`] method, and
94 /// append a [`&str`] with the [`push_str`] method:
97 /// let mut hello = String::from("Hello, ");
100 /// hello.push_str("orld!");
103 /// [`char`]: ../../std/primitive.char.html
104 /// [`push`]: #method.push
105 /// [`push_str`]: #method.push_str
107 /// If you have a vector of UTF-8 bytes, you can create a `String` from it with
108 /// the [`from_utf8`] method:
111 /// // some bytes, in a vector
112 /// let sparkle_heart = vec![240, 159, 146, 150];
114 /// // We know these bytes are valid, so we'll use `unwrap()`.
115 /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
117 /// assert_eq!("💖", sparkle_heart);
120 /// [`from_utf8`]: #method.from_utf8
124 /// `String`s are always valid UTF-8. This has a few implications, the first of
125 /// which is that if you need a non-UTF-8 string, consider [`OsString`]. It is
126 /// similar, but without the UTF-8 constraint. The second implication is that
127 /// you cannot index into a `String`:
132 /// println!("The first letter of s is {}", s[0]); // ERROR!!!
135 /// [`OsString`]: ../../std/ffi/struct.OsString.html
137 /// Indexing is intended to be a constant-time operation, but UTF-8 encoding
138 /// does not allow us to do this. Furthermore, it's not clear what sort of
139 /// thing the index should return: a byte, a codepoint, or a grapheme cluster.
140 /// The [`bytes`] and [`chars`] methods return iterators over the first
141 /// two, respectively.
143 /// [`bytes`]: #method.bytes
144 /// [`chars`]: #method.chars
148 /// `String`s implement [`Deref`]`<Target=str>`, and so inherit all of [`str`]'s
149 /// methods. In addition, this means that you can pass a `String` to any
150 /// function which takes a [`&str`] by using an ampersand (`&`):
153 /// fn takes_str(s: &str) { }
155 /// let s = String::from("Hello");
160 /// [`&str`]: ../../std/primitive.str.html
161 /// [`Deref`]: ../../std/ops/trait.Deref.html
163 /// This will create a [`&str`] from the `String` and pass it in. This
164 /// conversion is very inexpensive, and so generally, functions will accept
165 /// [`&str`]s as arguments unless they need a `String` for some specific reason.
170 /// A `String` is made up of three components: a pointer to some bytes, a
171 /// length, and a capacity. The pointer points to an internal buffer `String`
172 /// uses to store its data. The length is the number of bytes currently stored
173 /// in the buffer, and the capacity is the size of the buffer in bytes. As such,
174 /// the length will always be less than or equal to the capacity.
176 /// This buffer is always stored on the heap.
178 /// You can look at these with the [`as_ptr`], [`len`], and [`capacity`]
184 /// let story = String::from("Once upon a time...");
186 /// let ptr = story.as_ptr();
187 /// let len = story.len();
188 /// let capacity = story.capacity();
190 /// // story has nineteen bytes
191 /// assert_eq!(19, len);
193 /// // Now that we have our parts, we throw the story away.
194 /// mem::forget(story);
196 /// // We can re-build a String out of ptr, len, and capacity. This is all
197 /// // unsafe because we are responsible for making sure the components are
199 /// let s = unsafe { String::from_raw_parts(ptr as *mut _, len, capacity) } ;
201 /// assert_eq!(String::from("Once upon a time..."), s);
204 /// [`as_ptr`]: #method.as_ptr
205 /// [`len`]: #method.len
206 /// [`capacity`]: #method.capacity
208 /// If a `String` has enough capacity, adding elements to it will not
209 /// re-allocate. For example, consider this program:
212 /// let mut s = String::new();
214 /// println!("{}", s.capacity());
217 /// s.push_str("hello");
218 /// println!("{}", s.capacity());
222 /// This will output the following:
233 /// At first, we have no memory allocated at all, but as we append to the
234 /// string, it increases its capacity appropriately. If we instead use the
235 /// [`with_capacity`] method to allocate the correct capacity initially:
238 /// let mut s = String::with_capacity(25);
240 /// println!("{}", s.capacity());
243 /// s.push_str("hello");
244 /// println!("{}", s.capacity());
248 /// [`with_capacity`]: #method.with_capacity
250 /// We end up with a different output:
261 /// Here, there's no need to allocate more memory inside the loop.
262 #[derive(PartialOrd, Eq, Ord)]
263 #[stable(feature = "rust1", since = "1.0.0")]
268 /// A possible error value when converting a `String` from a UTF-8 byte vector.
270 /// This type is the error type for the [`from_utf8`] method on [`String`]. It
271 /// is designed in such a way to carefully avoid reallocations: the
272 /// [`into_bytes`] method will give back the byte vector that was used in the
273 /// conversion attempt.
275 /// [`from_utf8`]: struct.String.html#method.from_utf8
276 /// [`String`]: struct.String.html
277 /// [`into_bytes`]: struct.FromUtf8Error.html#method.into_bytes
279 /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
280 /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
281 /// an analogue to `FromUtf8Error`, and you can get one from a `FromUtf8Error`
282 /// through the [`utf8_error`] method.
284 /// [`Utf8Error`]: ../../std/str/struct.Utf8Error.html
285 /// [`std::str`]: ../../std/str/index.html
286 /// [`u8`]: ../../std/primitive.u8.html
287 /// [`&str`]: ../../std/primitive.str.html
288 /// [`utf8_error`]: #method.utf8_error
295 /// // some invalid bytes, in a vector
296 /// let bytes = vec![0, 159];
298 /// let value = String::from_utf8(bytes);
300 /// assert!(value.is_err());
301 /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
303 #[stable(feature = "rust1", since = "1.0.0")]
305 pub struct FromUtf8Error {
310 /// A possible error value when converting a `String` from a UTF-16 byte slice.
312 /// This type is the error type for the [`from_utf16`] method on [`String`].
314 /// [`from_utf16`]: struct.String.html#method.from_utf16
315 /// [`String`]: struct.String.html
322 /// // 𝄞mu<invalid>ic
323 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
324 /// 0xD800, 0x0069, 0x0063];
326 /// assert!(String::from_utf16(v).is_err());
328 #[stable(feature = "rust1", since = "1.0.0")]
330 pub struct FromUtf16Error(());
333 /// Creates a new empty `String`.
335 /// Given that the `String` is empty, this will not allocate any initial
336 /// buffer. While that means that this initial operation is very
337 /// inexpensive, but may cause excessive allocation later, when you add
338 /// data. If you have an idea of how much data the `String` will hold,
339 /// consider the [`with_capacity`] method to prevent excessive
342 /// [`with_capacity`]: #method.with_capacity
349 /// let s = String::new();
352 #[stable(feature = "rust1", since = "1.0.0")]
353 pub fn new() -> String {
354 String { vec: Vec::new() }
357 /// Creates a new empty `String` with a particular capacity.
359 /// `String`s have an internal buffer to hold their data. The capacity is
360 /// the length of that buffer, and can be queried with the [`capacity`]
361 /// method. This method creates an empty `String`, but one with an initial
362 /// buffer that can hold `capacity` bytes. This is useful when you may be
363 /// appending a bunch of data to the `String`, reducing the number of
364 /// reallocations it needs to do.
366 /// [`capacity`]: #method.capacity
368 /// If the given capacity is `0`, no allocation will occur, and this method
369 /// is identical to the [`new`] method.
371 /// [`new`]: #method.new
378 /// let mut s = String::with_capacity(10);
380 /// // The String contains no chars, even though it has capacity for more
381 /// assert_eq!(s.len(), 0);
383 /// // These are all done without reallocating...
384 /// let cap = s.capacity();
389 /// assert_eq!(s.capacity(), cap);
391 /// // ...but this may make the vector reallocate
395 #[stable(feature = "rust1", since = "1.0.0")]
396 pub fn with_capacity(capacity: usize) -> String {
397 String { vec: Vec::with_capacity(capacity) }
400 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
401 // required for this method definition, is not available. Since we don't
402 // require this method for testing purposes, I'll just stub it
403 // NB see the slice::hack module in slice.rs for more information
406 pub fn from_str(_: &str) -> String {
407 panic!("not available with cfg(test)");
410 /// Converts a vector of bytes to a `String`.
412 /// A string slice ([`&str`]) is made of bytes ([`u8`]), and a vector of bytes
413 /// ([`Vec<u8>`]) is made of bytes, so this function converts between the
414 /// two. Not all byte slices are valid `String`s, however: `String`
415 /// requires that it is valid UTF-8. `from_utf8()` checks to ensure that
416 /// the bytes are valid UTF-8, and then does the conversion.
418 /// [`&str`]: ../../std/primitive.str.html
419 /// [`u8`]: ../../std/primitive.u8.html
420 /// [`Vec<u8>`]: ../../std/vec/struct.Vec.html
422 /// If you are sure that the byte slice is valid UTF-8, and you don't want
423 /// to incur the overhead of the validity check, there is an unsafe version
424 /// of this function, [`from_utf8_unchecked`], which has the same behavior
425 /// but skips the check.
427 /// [`from_utf8_unchecked`]: struct.String.html#method.from_utf8_unchecked
429 /// This method will take care to not copy the vector, for efficiency's
432 /// If you need a `&str` instead of a `String`, consider
433 /// [`str::from_utf8`].
435 /// [`str::from_utf8`]: ../../std/str/fn.from_utf8.html
437 /// The inverse of this method is [`as_bytes`].
439 /// [`as_bytes`]: #method.as_bytes
443 /// Returns `Err` if the slice is not UTF-8 with a description as to why the
444 /// provided bytes are not UTF-8. The vector you moved in is also included.
451 /// // some bytes, in a vector
452 /// let sparkle_heart = vec![240, 159, 146, 150];
454 /// // We know these bytes are valid, so we'll use `unwrap()`.
455 /// let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
457 /// assert_eq!("💖", sparkle_heart);
463 /// // some invalid bytes, in a vector
464 /// let sparkle_heart = vec![0, 159, 146, 150];
466 /// assert!(String::from_utf8(sparkle_heart).is_err());
469 /// See the docs for [`FromUtf8Error`] for more details on what you can do
472 /// [`FromUtf8Error`]: struct.FromUtf8Error.html
474 #[stable(feature = "rust1", since = "1.0.0")]
475 pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error> {
476 match str::from_utf8(&vec) {
477 Ok(..) => Ok(String { vec: vec }),
487 /// Converts a slice of bytes to a string, including invalid characters.
489 /// Strings are made of bytes ([`u8`]), and a slice of bytes
490 /// ([`&[u8]`][byteslice]) is made of bytes, so this function converts
491 /// between the two. Not all byte slices are valid strings, however: strings
492 /// are required to be valid UTF-8. During this conversion,
493 /// `from_utf8_lossy()` will replace any invalid UTF-8 sequences with
494 /// `U+FFFD REPLACEMENT CHARACTER`, which looks like this: �
496 /// [`u8`]: ../../std/primitive.u8.html
497 /// [byteslice]: ../../std/primitive.slice.html
499 /// If you are sure that the byte slice is valid UTF-8, and you don't want
500 /// to incur the overhead of the conversion, there is an unsafe version
501 /// of this function, [`from_utf8_unchecked`], which has the same behavior
502 /// but skips the checks.
504 /// [`from_utf8_unchecked`]: struct.String.html#method.from_utf8_unchecked
506 /// This function returns a [`Cow<'a, str>`]. If our byte slice is invalid
507 /// UTF-8, then we need to insert the replacement characters, which will
508 /// change the size of the string, and hence, require a `String`. But if
509 /// it's already valid UTF-8, we don't need a new allocation. This return
510 /// type allows us to handle both cases.
512 /// [`Cow<'a, str>`]: ../../std/borrow/enum.Cow.html
519 /// // some bytes, in a vector
520 /// let sparkle_heart = vec![240, 159, 146, 150];
522 /// let sparkle_heart = String::from_utf8_lossy(&sparkle_heart);
524 /// assert_eq!("💖", sparkle_heart);
530 /// // some invalid bytes
531 /// let input = b"Hello \xF0\x90\x80World";
532 /// let output = String::from_utf8_lossy(input);
534 /// assert_eq!("Hello �World", output);
536 #[stable(feature = "rust1", since = "1.0.0")]
537 pub fn from_utf8_lossy<'a>(v: &'a [u8]) -> Cow<'a, str> {
539 match str::from_utf8(v) {
540 Ok(s) => return Cow::Borrowed(s),
541 Err(e) => i = e.valid_up_to(),
544 const TAG_CONT_U8: u8 = 128;
545 const REPLACEMENT: &'static [u8] = b"\xEF\xBF\xBD"; // U+FFFD in UTF-8
547 fn unsafe_get(xs: &[u8], i: usize) -> u8 {
548 unsafe { *xs.get_unchecked(i) }
550 fn safe_get(xs: &[u8], i: usize, total: usize) -> u8 {
551 if i >= total { 0 } else { unsafe_get(xs, i) }
554 let mut res = String::with_capacity(total);
557 unsafe { res.as_mut_vec().extend_from_slice(&v[..i]) };
560 // subseqidx is the index of the first byte of the subsequence we're
561 // looking at. It's used to copy a bunch of contiguous good codepoints
562 // at once instead of copying them one by one.
563 let mut subseqidx = i;
567 let byte = unsafe_get(v, i);
570 macro_rules! error { () => ({
573 res.as_mut_vec().extend_from_slice(&v[subseqidx..i_]);
576 res.as_mut_vec().extend_from_slice(REPLACEMENT);
581 // subseqidx handles this
583 let w = core_str::utf8_char_width(byte);
587 if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
594 match (byte, safe_get(v, i, total)) {
595 (0xE0, 0xA0...0xBF) => (),
596 (0xE1...0xEC, 0x80...0xBF) => (),
597 (0xED, 0x80...0x9F) => (),
598 (0xEE...0xEF, 0x80...0xBF) => (),
605 if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
612 match (byte, safe_get(v, i, total)) {
613 (0xF0, 0x90...0xBF) => (),
614 (0xF1...0xF3, 0x80...0xBF) => (),
615 (0xF4, 0x80...0x8F) => (),
622 if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
627 if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
640 if subseqidx < total {
641 unsafe { res.as_mut_vec().extend_from_slice(&v[subseqidx..total]) };
646 /// Decode a UTF-16 encoded vector `v` into a `String`, returning `Err`
647 /// if `v` contains any invalid data.
655 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
656 /// 0x0073, 0x0069, 0x0063];
657 /// assert_eq!(String::from("𝄞music"),
658 /// String::from_utf16(v).unwrap());
660 /// // 𝄞mu<invalid>ic
661 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
662 /// 0xD800, 0x0069, 0x0063];
663 /// assert!(String::from_utf16(v).is_err());
665 #[stable(feature = "rust1", since = "1.0.0")]
666 pub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error> {
667 decode_utf16(v.iter().cloned()).collect::<Result<_, _>>().map_err(|_| FromUtf16Error(()))
670 /// Decode a UTF-16 encoded vector `v` into a string, replacing
671 /// invalid data with the replacement character (U+FFFD).
678 /// // 𝄞mus<invalid>ic<invalid>
679 /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
680 /// 0x0073, 0xDD1E, 0x0069, 0x0063,
683 /// assert_eq!(String::from("𝄞mus\u{FFFD}ic\u{FFFD}"),
684 /// String::from_utf16_lossy(v));
687 #[stable(feature = "rust1", since = "1.0.0")]
688 pub fn from_utf16_lossy(v: &[u16]) -> String {
689 decode_utf16(v.iter().cloned()).map(|r| r.unwrap_or(REPLACEMENT_CHARACTER)).collect()
692 /// Creates a new `String` from a length, capacity, and pointer.
696 /// This is highly unsafe, due to the number of invariants that aren't
699 /// * The memory at `ptr` needs to have been previously allocated by the
700 /// same allocator the standard library uses.
701 /// * `length` needs to be less than or equal to `capacity`.
702 /// * `capacity` needs to be the correct value.
704 /// Violating these may cause problems like corrupting the allocator's
705 /// internal datastructures.
707 /// The ownership of `ptr` is effectively transferred to the
708 /// `String` which may then deallocate, reallocate or change the
709 /// contents of memory pointed to by the pointer at will. Ensure
710 /// that nothing else uses the pointer after calling this
721 /// let s = String::from("hello");
722 /// let ptr = s.as_ptr();
723 /// let len = s.len();
724 /// let capacity = s.capacity();
728 /// let s = String::from_raw_parts(ptr as *mut _, len, capacity);
730 /// assert_eq!(String::from("hello"), s);
734 #[stable(feature = "rust1", since = "1.0.0")]
735 pub unsafe fn from_raw_parts(buf: *mut u8, length: usize, capacity: usize) -> String {
736 String { vec: Vec::from_raw_parts(buf, length, capacity) }
739 /// Converts a vector of bytes to a `String` without checking that the
740 /// string contains valid UTF-8.
742 /// See the safe version, [`from_utf8`], for more details.
744 /// [`from_utf8`]: struct.String.html#method.from_utf8
748 /// This function is unsafe because it does not check that the bytes passed
749 /// to it are valid UTF-8. If this constraint is violated, it may cause
750 /// memory unsafety issues with future users of the `String`, as the rest of
751 /// the standard library assumes that `String`s are valid UTF-8.
758 /// // some bytes, in a vector
759 /// let sparkle_heart = vec![240, 159, 146, 150];
761 /// let sparkle_heart = unsafe {
762 /// String::from_utf8_unchecked(sparkle_heart)
765 /// assert_eq!("💖", sparkle_heart);
768 #[stable(feature = "rust1", since = "1.0.0")]
769 pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String {
770 String { vec: bytes }
773 /// Converts a `String` into a byte vector.
775 /// This consumes the `String`, so we do not need to copy its contents.
782 /// let s = String::from("hello");
783 /// let bytes = s.into_bytes();
785 /// assert_eq!(&[104, 101, 108, 108, 111][..], &bytes[..]);
788 #[stable(feature = "rust1", since = "1.0.0")]
789 pub fn into_bytes(self) -> Vec<u8> {
793 /// Extracts a string slice containing the entire string.
795 #[stable(feature = "string_as_str", since = "1.7.0")]
796 pub fn as_str(&self) -> &str {
800 /// Extracts a string slice containing the entire string.
802 #[stable(feature = "string_as_str", since = "1.7.0")]
803 pub fn as_mut_str(&mut self) -> &mut str {
807 /// Appends a given string slice onto the end of this `String`.
814 /// let mut s = String::from("foo");
816 /// s.push_str("bar");
818 /// assert_eq!("foobar", s);
821 #[stable(feature = "rust1", since = "1.0.0")]
822 pub fn push_str(&mut self, string: &str) {
823 self.vec.extend_from_slice(string.as_bytes())
826 /// Returns this `String`'s capacity, in bytes.
833 /// let s = String::with_capacity(10);
835 /// assert!(s.capacity() >= 10);
838 #[stable(feature = "rust1", since = "1.0.0")]
839 pub fn capacity(&self) -> usize {
843 /// Ensures that this `String`'s capacity is at least `additional` bytes
844 /// larger than its length.
846 /// The capacity may be increased by more than `additional` bytes if it
847 /// chooses, to prevent frequent reallocations.
849 /// If you do not want this "at least" behavior, see the [`reserve_exact`]
852 /// [`reserve_exact`]: #method.reserve_exact
856 /// Panics if the new capacity overflows `usize`.
863 /// let mut s = String::new();
867 /// assert!(s.capacity() >= 10);
870 /// This may not actually increase the capacity:
873 /// let mut s = String::with_capacity(10);
877 /// // s now has a length of 2 and a capacity of 10
878 /// assert_eq!(2, s.len());
879 /// assert_eq!(10, s.capacity());
881 /// // Since we already have an extra 8 capacity, calling this...
884 /// // ... doesn't actually increase.
885 /// assert_eq!(10, s.capacity());
888 #[stable(feature = "rust1", since = "1.0.0")]
889 pub fn reserve(&mut self, additional: usize) {
890 self.vec.reserve(additional)
893 /// Ensures that this `String`'s capacity is `additional` bytes
894 /// larger than its length.
896 /// Consider using the [`reserve`] method unless you absolutely know
897 /// better than the allocator.
899 /// [`reserve`]: #method.reserve
903 /// Panics if the new capacity overflows `usize`.
910 /// let mut s = String::new();
912 /// s.reserve_exact(10);
914 /// assert!(s.capacity() >= 10);
917 /// This may not actually increase the capacity:
920 /// let mut s = String::with_capacity(10);
924 /// // s now has a length of 2 and a capacity of 10
925 /// assert_eq!(2, s.len());
926 /// assert_eq!(10, s.capacity());
928 /// // Since we already have an extra 8 capacity, calling this...
929 /// s.reserve_exact(8);
931 /// // ... doesn't actually increase.
932 /// assert_eq!(10, s.capacity());
935 #[stable(feature = "rust1", since = "1.0.0")]
936 pub fn reserve_exact(&mut self, additional: usize) {
937 self.vec.reserve_exact(additional)
940 /// Shrinks the capacity of this `String` to match its length.
947 /// let mut s = String::from("foo");
950 /// assert!(s.capacity() >= 100);
952 /// s.shrink_to_fit();
953 /// assert_eq!(3, s.capacity());
956 #[stable(feature = "rust1", since = "1.0.0")]
957 pub fn shrink_to_fit(&mut self) {
958 self.vec.shrink_to_fit()
961 /// Appends the given `char` to the end of this `String`.
968 /// let mut s = String::from("abc");
974 /// assert_eq!("abc123", s);
977 #[stable(feature = "rust1", since = "1.0.0")]
978 pub fn push(&mut self, ch: char) {
979 match ch.len_utf8() {
980 1 => self.vec.push(ch as u8),
981 _ => self.vec.extend_from_slice(ch.encode_utf8(&mut [0; 4]).as_bytes()),
985 /// Returns a byte slice of this `String`'s contents.
987 /// The inverse of this method is [`from_utf8`].
989 /// [`from_utf8`]: #method.from_utf8
996 /// let s = String::from("hello");
998 /// assert_eq!(&[104, 101, 108, 108, 111], s.as_bytes());
1001 #[stable(feature = "rust1", since = "1.0.0")]
1002 pub fn as_bytes(&self) -> &[u8] {
1006 /// Shortens this `String` to the specified length.
1008 /// If `new_len` is greater than the string's current length, this has no
1011 /// Note that this method has no effect on the allocated capacity
1016 /// Panics if `new_len` does not lie on a [`char`] boundary.
1018 /// [`char`]: ../../std/primitive.char.html
1025 /// let mut s = String::from("hello");
1029 /// assert_eq!("he", s);
1032 #[stable(feature = "rust1", since = "1.0.0")]
1033 pub fn truncate(&mut self, new_len: usize) {
1034 if new_len <= self.len() {
1035 assert!(self.is_char_boundary(new_len));
1036 self.vec.truncate(new_len)
1040 /// Removes the last character from the string buffer and returns it.
1042 /// Returns `None` if this `String` is empty.
1049 /// let mut s = String::from("foo");
1051 /// assert_eq!(s.pop(), Some('o'));
1052 /// assert_eq!(s.pop(), Some('o'));
1053 /// assert_eq!(s.pop(), Some('f'));
1055 /// assert_eq!(s.pop(), None);
1058 #[stable(feature = "rust1", since = "1.0.0")]
1059 pub fn pop(&mut self) -> Option<char> {
1060 let ch = match self.chars().rev().next() {
1062 None => return None,
1064 let newlen = self.len() - ch.len_utf8();
1066 self.vec.set_len(newlen);
1071 /// Removes a `char` from this `String` at a byte position and returns it.
1073 /// This is an `O(n)` operation, as it requires copying every element in the
1078 /// Panics if `idx` is larger than or equal to the `String`'s length,
1079 /// or if it does not lie on a [`char`] boundary.
1081 /// [`char`]: ../../std/primitive.char.html
1088 /// let mut s = String::from("foo");
1090 /// assert_eq!(s.remove(0), 'f');
1091 /// assert_eq!(s.remove(1), 'o');
1092 /// assert_eq!(s.remove(0), 'o');
1095 #[stable(feature = "rust1", since = "1.0.0")]
1096 pub fn remove(&mut self, idx: usize) -> char {
1097 let ch = match self[idx..].chars().next() {
1099 None => panic!("cannot remove a char from the end of a string"),
1102 let next = idx + ch.len_utf8();
1103 let len = self.len();
1105 ptr::copy(self.vec.as_ptr().offset(next as isize),
1106 self.vec.as_mut_ptr().offset(idx as isize),
1108 self.vec.set_len(len - (next - idx));
1113 /// Inserts a character into this `String` at a byte position.
1115 /// This is an `O(n)` operation as it requires copying every element in the
1120 /// Panics if `idx` is larger than the `String`'s length, or if it does not
1121 /// lie on a [`char`] boundary.
1123 /// [`char`]: ../../std/primitive.char.html
1130 /// let mut s = String::with_capacity(3);
1132 /// s.insert(0, 'f');
1133 /// s.insert(1, 'o');
1134 /// s.insert(2, 'o');
1136 /// assert_eq!("foo", s);
1139 #[stable(feature = "rust1", since = "1.0.0")]
1140 pub fn insert(&mut self, idx: usize, ch: char) {
1141 assert!(self.is_char_boundary(idx));
1142 let mut bits = [0; 4];
1143 let bits = ch.encode_utf8(&mut bits).as_bytes();
1146 self.insert_bytes(idx, bits);
1150 unsafe fn insert_bytes(&mut self, idx: usize, bytes: &[u8]) {
1151 let len = self.len();
1152 let amt = bytes.len();
1153 self.vec.reserve(amt);
1155 ptr::copy(self.vec.as_ptr().offset(idx as isize),
1156 self.vec.as_mut_ptr().offset((idx + amt) as isize),
1158 ptr::copy(bytes.as_ptr(),
1159 self.vec.as_mut_ptr().offset(idx as isize),
1161 self.vec.set_len(len + amt);
1164 /// Inserts a string slice into this `String` at a byte position.
1166 /// This is an `O(n)` operation as it requires copying every element in the
1171 /// Panics if `idx` is larger than the `String`'s length, or if it does not
1172 /// lie on a [`char`] boundary.
1174 /// [`char`]: ../../std/primitive.char.html
1181 /// let mut s = String::from("bar");
1183 /// s.insert_str(0, "foo");
1185 /// assert_eq!("foobar", s);
1188 #[stable(feature = "insert_str", since = "1.16.0")]
1189 pub fn insert_str(&mut self, idx: usize, string: &str) {
1190 assert!(self.is_char_boundary(idx));
1193 self.insert_bytes(idx, string.as_bytes());
1197 /// Returns a mutable reference to the contents of this `String`.
1201 /// This function is unsafe because it does not check that the bytes passed
1202 /// to it are valid UTF-8. If this constraint is violated, it may cause
1203 /// memory unsafety issues with future users of the `String`, as the rest of
1204 /// the standard library assumes that `String`s are valid UTF-8.
1211 /// let mut s = String::from("hello");
1214 /// let vec = s.as_mut_vec();
1215 /// assert_eq!(&[104, 101, 108, 108, 111][..], &vec[..]);
1219 /// assert_eq!(s, "olleh");
1222 #[stable(feature = "rust1", since = "1.0.0")]
1223 pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1227 /// Returns the length of this `String`, in bytes.
1234 /// let a = String::from("foo");
1236 /// assert_eq!(a.len(), 3);
1239 #[stable(feature = "rust1", since = "1.0.0")]
1240 pub fn len(&self) -> usize {
1244 /// Returns `true` if this `String` has a length of zero.
1246 /// Returns `false` otherwise.
1253 /// let mut v = String::new();
1254 /// assert!(v.is_empty());
1257 /// assert!(!v.is_empty());
1260 #[stable(feature = "rust1", since = "1.0.0")]
1261 pub fn is_empty(&self) -> bool {
1265 /// Splits the string into two at the given index.
1267 /// Returns a newly allocated `String`. `self` contains bytes `[0, at)`, and
1268 /// the returned `String` contains bytes `[at, len)`. `at` must be on the
1269 /// boundary of a UTF-8 code point.
1271 /// Note that the capacity of `self` does not change.
1275 /// Panics if `at` is not on a `UTF-8` code point boundary, or if it is beyond the last
1276 /// code point of the string.
1282 /// let mut hello = String::from("Hello, World!");
1283 /// let world = hello.split_off(7);
1284 /// assert_eq!(hello, "Hello, ");
1285 /// assert_eq!(world, "World!");
1289 #[stable(feature = "string_split_off", since = "1.16.0")]
1290 pub fn split_off(&mut self, at: usize) -> String {
1291 assert!(self.is_char_boundary(at));
1292 let other = self.vec.split_off(at);
1293 unsafe { String::from_utf8_unchecked(other) }
1296 /// Truncates this `String`, removing all contents.
1298 /// While this means the `String` will have a length of zero, it does not
1299 /// touch its capacity.
1306 /// let mut s = String::from("foo");
1310 /// assert!(s.is_empty());
1311 /// assert_eq!(0, s.len());
1312 /// assert_eq!(3, s.capacity());
1315 #[stable(feature = "rust1", since = "1.0.0")]
1316 pub fn clear(&mut self) {
1320 /// Creates a draining iterator that removes the specified range in the string
1321 /// and yields the removed chars.
1323 /// Note: The element range is removed even if the iterator is not
1324 /// consumed until the end.
1328 /// Panics if the starting point or end point do not lie on a [`char`]
1329 /// boundary, or if they're out of bounds.
1331 /// [`char`]: ../../std/primitive.char.html
1338 /// let mut s = String::from("α is alpha, β is beta");
1339 /// let beta_offset = s.find('β').unwrap_or(s.len());
1341 /// // Remove the range up until the β from the string
1342 /// let t: String = s.drain(..beta_offset).collect();
1343 /// assert_eq!(t, "α is alpha, ");
1344 /// assert_eq!(s, "β is beta");
1346 /// // A full range clears the string
1348 /// assert_eq!(s, "");
1350 #[stable(feature = "drain", since = "1.6.0")]
1351 pub fn drain<R>(&mut self, range: R) -> Drain
1352 where R: RangeArgument<usize>
1356 // The String version of Drain does not have the memory safety issues
1357 // of the vector version. The data is just plain bytes.
1358 // Because the range removal happens in Drop, if the Drain iterator is leaked,
1359 // the removal will not happen.
1360 let len = self.len();
1361 let start = match range.start() {
1363 Excluded(&n) => n + 1,
1366 let end = match range.end() {
1367 Included(&n) => n + 1,
1372 // Take out two simultaneous borrows. The &mut String won't be accessed
1373 // until iteration is over, in Drop.
1374 let self_ptr = self as *mut _;
1375 // slicing does the appropriate bounds checks
1376 let chars_iter = self[start..end].chars();
1386 /// Creates a splicing iterator that removes the specified range in the string,
1387 /// replaces with the given string, and yields the removed chars.
1388 /// The given string doesn’t need to be the same length as the range.
1390 /// Note: The element range is removed when the `Splice` is dropped,
1391 /// even if the iterator is not consumed until the end.
1395 /// Panics if the starting point or end point do not lie on a [`char`]
1396 /// boundary, or if they're out of bounds.
1398 /// [`char`]: ../../std/primitive.char.html
1405 /// #![feature(splice)]
1406 /// let mut s = String::from("α is alpha, β is beta");
1407 /// let beta_offset = s.find('β').unwrap_or(s.len());
1409 /// // Replace the range up until the β from the string
1410 /// let t: String = s.splice(..beta_offset, "Α is capital alpha; ").collect();
1411 /// assert_eq!(t, "α is alpha, ");
1412 /// assert_eq!(s, "Α is capital alpha; β is beta");
1414 #[unstable(feature = "splice", reason = "recently added", issue = "32310")]
1415 pub fn splice<'a, 'b, R>(&'a mut self, range: R, replace_with: &'b str) -> Splice<'a, 'b>
1416 where R: RangeArgument<usize>
1420 // The String version of Splice does not have the memory safety issues
1421 // of the vector version. The data is just plain bytes.
1422 // Because the range removal happens in Drop, if the Splice iterator is leaked,
1423 // the removal will not happen.
1424 let len = self.len();
1425 let start = match range.start() {
1427 Excluded(&n) => n + 1,
1430 let end = match range.end() {
1431 Included(&n) => n + 1,
1436 // Take out two simultaneous borrows. The &mut String won't be accessed
1437 // until iteration is over, in Drop.
1438 let self_ptr = self as *mut _;
1439 // slicing does the appropriate bounds checks
1440 let chars_iter = self[start..end].chars();
1447 replace_with: replace_with
1451 /// Converts this `String` into a `Box<str>`.
1453 /// This will drop any excess capacity.
1460 /// let s = String::from("hello");
1462 /// let b = s.into_boxed_str();
1464 #[stable(feature = "box_str", since = "1.4.0")]
1465 pub fn into_boxed_str(self) -> Box<str> {
1466 let slice = self.vec.into_boxed_slice();
1467 unsafe { alloc_str::from_boxed_utf8_unchecked(slice) }
1471 impl FromUtf8Error {
1472 /// Returns a slice of [`u8`]s bytes that were attempted to convert to a `String`.
1479 /// #![feature(from_utf8_error_as_bytes)]
1480 /// // some invalid bytes, in a vector
1481 /// let bytes = vec![0, 159];
1483 /// let value = String::from_utf8(bytes);
1485 /// assert_eq!(&[0, 159], value.unwrap_err().as_bytes());
1487 #[unstable(feature = "from_utf8_error_as_bytes", reason = "recently added", issue = "40895")]
1488 pub fn as_bytes(&self) -> &[u8] {
1492 /// Returns the bytes that were attempted to convert to a `String`.
1494 /// This method is carefully constructed to avoid allocation. It will
1495 /// consume the error, moving out the bytes, so that a copy of the bytes
1496 /// does not need to be made.
1503 /// // some invalid bytes, in a vector
1504 /// let bytes = vec![0, 159];
1506 /// let value = String::from_utf8(bytes);
1508 /// assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());
1510 #[stable(feature = "rust1", since = "1.0.0")]
1511 pub fn into_bytes(self) -> Vec<u8> {
1515 /// Fetch a `Utf8Error` to get more details about the conversion failure.
1517 /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
1518 /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
1519 /// an analogue to `FromUtf8Error`. See its documentation for more details
1522 /// [`Utf8Error`]: ../../std/str/struct.Utf8Error.html
1523 /// [`std::str`]: ../../std/str/index.html
1524 /// [`u8`]: ../../std/primitive.u8.html
1525 /// [`&str`]: ../../std/primitive.str.html
1532 /// // some invalid bytes, in a vector
1533 /// let bytes = vec![0, 159];
1535 /// let error = String::from_utf8(bytes).unwrap_err().utf8_error();
1537 /// // the first byte is invalid here
1538 /// assert_eq!(1, error.valid_up_to());
1540 #[stable(feature = "rust1", since = "1.0.0")]
1541 pub fn utf8_error(&self) -> Utf8Error {
1546 #[stable(feature = "rust1", since = "1.0.0")]
1547 impl fmt::Display for FromUtf8Error {
1548 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1549 fmt::Display::fmt(&self.error, f)
1553 #[stable(feature = "rust1", since = "1.0.0")]
1554 impl fmt::Display for FromUtf16Error {
1555 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1556 fmt::Display::fmt("invalid utf-16: lone surrogate found", f)
1560 #[stable(feature = "rust1", since = "1.0.0")]
1561 impl Clone for String {
1562 fn clone(&self) -> Self {
1563 String { vec: self.vec.clone() }
1566 fn clone_from(&mut self, source: &Self) {
1567 self.vec.clone_from(&source.vec);
1571 #[stable(feature = "rust1", since = "1.0.0")]
1572 impl FromIterator<char> for String {
1573 fn from_iter<I: IntoIterator<Item = char>>(iter: I) -> String {
1574 let mut buf = String::new();
1580 #[stable(feature = "string_from_iter_by_ref", since = "1.17.0")]
1581 impl<'a> FromIterator<&'a char> for String {
1582 fn from_iter<I: IntoIterator<Item = &'a char>>(iter: I) -> String {
1583 let mut buf = String::new();
1589 #[stable(feature = "rust1", since = "1.0.0")]
1590 impl<'a> FromIterator<&'a str> for String {
1591 fn from_iter<I: IntoIterator<Item = &'a str>>(iter: I) -> String {
1592 let mut buf = String::new();
1598 #[stable(feature = "extend_string", since = "1.4.0")]
1599 impl FromIterator<String> for String {
1600 fn from_iter<I: IntoIterator<Item = String>>(iter: I) -> String {
1601 let mut buf = String::new();
1607 #[stable(feature = "rust1", since = "1.0.0")]
1608 impl Extend<char> for String {
1609 fn extend<I: IntoIterator<Item = char>>(&mut self, iter: I) {
1610 let iterator = iter.into_iter();
1611 let (lower_bound, _) = iterator.size_hint();
1612 self.reserve(lower_bound);
1613 for ch in iterator {
1619 #[stable(feature = "extend_ref", since = "1.2.0")]
1620 impl<'a> Extend<&'a char> for String {
1621 fn extend<I: IntoIterator<Item = &'a char>>(&mut self, iter: I) {
1622 self.extend(iter.into_iter().cloned());
1626 #[stable(feature = "rust1", since = "1.0.0")]
1627 impl<'a> Extend<&'a str> for String {
1628 fn extend<I: IntoIterator<Item = &'a str>>(&mut self, iter: I) {
1635 #[stable(feature = "extend_string", since = "1.4.0")]
1636 impl Extend<String> for String {
1637 fn extend<I: IntoIterator<Item = String>>(&mut self, iter: I) {
1644 /// A convenience impl that delegates to the impl for `&str`
1645 #[unstable(feature = "pattern",
1646 reason = "API not fully fleshed out and ready to be stabilized",
1648 impl<'a, 'b> Pattern<'a> for &'b String {
1649 type Searcher = <&'b str as Pattern<'a>>::Searcher;
1651 fn into_searcher(self, haystack: &'a str) -> <&'b str as Pattern<'a>>::Searcher {
1652 self[..].into_searcher(haystack)
1656 fn is_contained_in(self, haystack: &'a str) -> bool {
1657 self[..].is_contained_in(haystack)
1661 fn is_prefix_of(self, haystack: &'a str) -> bool {
1662 self[..].is_prefix_of(haystack)
1666 #[stable(feature = "rust1", since = "1.0.0")]
1667 impl PartialEq for String {
1669 fn eq(&self, other: &String) -> bool {
1670 PartialEq::eq(&self[..], &other[..])
1673 fn ne(&self, other: &String) -> bool {
1674 PartialEq::ne(&self[..], &other[..])
1678 macro_rules! impl_eq {
1679 ($lhs:ty, $rhs: ty) => {
1680 #[stable(feature = "rust1", since = "1.0.0")]
1681 impl<'a, 'b> PartialEq<$rhs> for $lhs {
1683 fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
1685 fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
1688 #[stable(feature = "rust1", since = "1.0.0")]
1689 impl<'a, 'b> PartialEq<$lhs> for $rhs {
1691 fn eq(&self, other: &$lhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
1693 fn ne(&self, other: &$lhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
1699 impl_eq! { String, str }
1700 impl_eq! { String, &'a str }
1701 impl_eq! { Cow<'a, str>, str }
1702 impl_eq! { Cow<'a, str>, &'b str }
1703 impl_eq! { Cow<'a, str>, String }
1705 #[stable(feature = "rust1", since = "1.0.0")]
1706 impl Default for String {
1707 /// Creates an empty `String`.
1709 fn default() -> String {
1714 #[stable(feature = "rust1", since = "1.0.0")]
1715 impl fmt::Display for String {
1717 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1718 fmt::Display::fmt(&**self, f)
1722 #[stable(feature = "rust1", since = "1.0.0")]
1723 impl fmt::Debug for String {
1725 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1726 fmt::Debug::fmt(&**self, f)
1730 #[stable(feature = "rust1", since = "1.0.0")]
1731 impl hash::Hash for String {
1733 fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
1734 (**self).hash(hasher)
1738 /// Implements the `+` operator for concatenating two strings.
1740 /// This consumes the `String` on the left-hand side and re-uses its buffer (growing it if
1741 /// necessary). This is done to avoid allocating a new `String` and copying the entire contents on
1742 /// every operation, which would lead to `O(n^2)` running time when building an `n`-byte string by
1743 /// repeated concatenation.
1745 /// The string on the right-hand side is only borrowed; its contents are copied into the returned
1750 /// Concatenating two `String`s takes the first by value and borrows the second:
1753 /// let a = String::from("hello");
1754 /// let b = String::from(" world");
1756 /// // `a` is moved and can no longer be used here.
1759 /// If you want to keep using the first `String`, you can clone it and append to the clone instead:
1762 /// let a = String::from("hello");
1763 /// let b = String::from(" world");
1764 /// let c = a.clone() + &b;
1765 /// // `a` is still valid here.
1768 /// Concatenating `&str` slices can be done by converting the first to a `String`:
1771 /// let a = "hello";
1772 /// let b = " world";
1773 /// let c = a.to_string() + b;
1775 #[stable(feature = "rust1", since = "1.0.0")]
1776 impl<'a> Add<&'a str> for String {
1777 type Output = String;
1780 fn add(mut self, other: &str) -> String {
1781 self.push_str(other);
1786 /// Implements the `+=` operator for appending to a `String`.
1788 /// This has the same behavior as the [`push_str`] method.
1790 /// [`push_str`]: struct.String.html#method.push_str
1791 #[stable(feature = "stringaddassign", since = "1.12.0")]
1792 impl<'a> AddAssign<&'a str> for String {
1794 fn add_assign(&mut self, other: &str) {
1795 self.push_str(other);
1799 #[stable(feature = "rust1", since = "1.0.0")]
1800 impl ops::Index<ops::Range<usize>> for String {
1804 fn index(&self, index: ops::Range<usize>) -> &str {
1808 #[stable(feature = "rust1", since = "1.0.0")]
1809 impl ops::Index<ops::RangeTo<usize>> for String {
1813 fn index(&self, index: ops::RangeTo<usize>) -> &str {
1817 #[stable(feature = "rust1", since = "1.0.0")]
1818 impl ops::Index<ops::RangeFrom<usize>> for String {
1822 fn index(&self, index: ops::RangeFrom<usize>) -> &str {
1826 #[stable(feature = "rust1", since = "1.0.0")]
1827 impl ops::Index<ops::RangeFull> for String {
1831 fn index(&self, _index: ops::RangeFull) -> &str {
1832 unsafe { str::from_utf8_unchecked(&self.vec) }
1835 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1836 impl ops::Index<ops::RangeInclusive<usize>> for String {
1840 fn index(&self, index: ops::RangeInclusive<usize>) -> &str {
1841 Index::index(&**self, index)
1844 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1845 impl ops::Index<ops::RangeToInclusive<usize>> for String {
1849 fn index(&self, index: ops::RangeToInclusive<usize>) -> &str {
1850 Index::index(&**self, index)
1854 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1855 impl ops::IndexMut<ops::Range<usize>> for String {
1857 fn index_mut(&mut self, index: ops::Range<usize>) -> &mut str {
1858 &mut self[..][index]
1861 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1862 impl ops::IndexMut<ops::RangeTo<usize>> for String {
1864 fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut str {
1865 &mut self[..][index]
1868 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1869 impl ops::IndexMut<ops::RangeFrom<usize>> for String {
1871 fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut str {
1872 &mut self[..][index]
1875 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1876 impl ops::IndexMut<ops::RangeFull> for String {
1878 fn index_mut(&mut self, _index: ops::RangeFull) -> &mut str {
1879 unsafe { str::from_utf8_unchecked_mut(&mut *self.vec) }
1882 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1883 impl ops::IndexMut<ops::RangeInclusive<usize>> for String {
1885 fn index_mut(&mut self, index: ops::RangeInclusive<usize>) -> &mut str {
1886 IndexMut::index_mut(&mut **self, index)
1889 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1890 impl ops::IndexMut<ops::RangeToInclusive<usize>> for String {
1892 fn index_mut(&mut self, index: ops::RangeToInclusive<usize>) -> &mut str {
1893 IndexMut::index_mut(&mut **self, index)
1897 #[stable(feature = "rust1", since = "1.0.0")]
1898 impl ops::Deref for String {
1902 fn deref(&self) -> &str {
1903 unsafe { str::from_utf8_unchecked(&self.vec) }
1907 #[stable(feature = "derefmut_for_string", since = "1.2.0")]
1908 impl ops::DerefMut for String {
1910 fn deref_mut(&mut self) -> &mut str {
1911 unsafe { str::from_utf8_unchecked_mut(&mut *self.vec) }
1915 /// An error when parsing a `String`.
1917 /// This `enum` is slightly awkward: it will never actually exist. This error is
1918 /// part of the type signature of the implementation of [`FromStr`] on
1919 /// [`String`]. The return type of [`from_str`], requires that an error be
1920 /// defined, but, given that a [`String`] can always be made into a new
1921 /// [`String`] without error, this type will never actually be returned. As
1922 /// such, it is only here to satisfy said signature, and is useless otherwise.
1924 /// [`FromStr`]: ../../std/str/trait.FromStr.html
1925 /// [`String`]: struct.String.html
1926 /// [`from_str`]: ../../std/str/trait.FromStr.html#tymethod.from_str
1927 #[stable(feature = "str_parse_error", since = "1.5.0")]
1929 pub enum ParseError {}
1931 #[stable(feature = "rust1", since = "1.0.0")]
1932 impl FromStr for String {
1933 type Err = ParseError;
1935 fn from_str(s: &str) -> Result<String, ParseError> {
1940 #[stable(feature = "str_parse_error", since = "1.5.0")]
1941 impl Clone for ParseError {
1942 fn clone(&self) -> ParseError {
1947 #[stable(feature = "str_parse_error", since = "1.5.0")]
1948 impl fmt::Debug for ParseError {
1949 fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result {
1954 #[stable(feature = "str_parse_error2", since = "1.8.0")]
1955 impl fmt::Display for ParseError {
1956 fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result {
1961 #[stable(feature = "str_parse_error", since = "1.5.0")]
1962 impl PartialEq for ParseError {
1963 fn eq(&self, _: &ParseError) -> bool {
1968 #[stable(feature = "str_parse_error", since = "1.5.0")]
1969 impl Eq for ParseError {}
1971 /// A trait for converting a value to a `String`.
1973 /// This trait is automatically implemented for any type which implements the
1974 /// [`Display`] trait. As such, `ToString` shouldn't be implemented directly:
1975 /// [`Display`] should be implemented instead, and you get the `ToString`
1976 /// implementation for free.
1978 /// [`Display`]: ../../std/fmt/trait.Display.html
1979 #[stable(feature = "rust1", since = "1.0.0")]
1980 pub trait ToString {
1981 /// Converts the given value to a `String`.
1989 /// let five = String::from("5");
1991 /// assert_eq!(five, i.to_string());
1993 #[stable(feature = "rust1", since = "1.0.0")]
1994 fn to_string(&self) -> String;
1999 /// In this implementation, the `to_string` method panics
2000 /// if the `Display` implementation returns an error.
2001 /// This indicates an incorrect `Display` implementation
2002 /// since `fmt::Write for String` never returns an error itself.
2003 #[stable(feature = "rust1", since = "1.0.0")]
2004 impl<T: fmt::Display + ?Sized> ToString for T {
2006 default fn to_string(&self) -> String {
2007 use core::fmt::Write;
2008 let mut buf = String::new();
2009 buf.write_fmt(format_args!("{}", self))
2010 .expect("a Display implementation return an error unexpectedly");
2011 buf.shrink_to_fit();
2016 #[stable(feature = "str_to_string_specialization", since = "1.9.0")]
2017 impl ToString for str {
2019 fn to_string(&self) -> String {
2024 #[stable(feature = "cow_str_to_string_specialization", since = "1.17.0")]
2025 impl<'a> ToString for Cow<'a, str> {
2027 fn to_string(&self) -> String {
2032 #[stable(feature = "string_to_string_specialization", since = "1.17.0")]
2033 impl ToString for String {
2035 fn to_string(&self) -> String {
2040 #[stable(feature = "rust1", since = "1.0.0")]
2041 impl AsRef<str> for String {
2043 fn as_ref(&self) -> &str {
2048 #[stable(feature = "rust1", since = "1.0.0")]
2049 impl AsRef<[u8]> for String {
2051 fn as_ref(&self) -> &[u8] {
2056 #[stable(feature = "rust1", since = "1.0.0")]
2057 impl<'a> From<&'a str> for String {
2058 fn from(s: &'a str) -> String {
2063 // note: test pulls in libstd, which causes errors here
2065 #[stable(feature = "string_from_box", since = "1.17.0")]
2066 impl From<Box<str>> for String {
2067 fn from(s: Box<str>) -> String {
2072 #[stable(feature = "box_from_str", since = "1.17.0")]
2073 impl Into<Box<str>> for String {
2074 fn into(self) -> Box<str> {
2075 self.into_boxed_str()
2079 #[stable(feature = "string_from_cow_str", since = "1.14.0")]
2080 impl<'a> From<Cow<'a, str>> for String {
2081 fn from(s: Cow<'a, str>) -> String {
2086 #[stable(feature = "rust1", since = "1.0.0")]
2087 impl<'a> From<&'a str> for Cow<'a, str> {
2089 fn from(s: &'a str) -> Cow<'a, str> {
2094 #[stable(feature = "rust1", since = "1.0.0")]
2095 impl<'a> From<String> for Cow<'a, str> {
2097 fn from(s: String) -> Cow<'a, str> {
2102 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2103 impl<'a> FromIterator<char> for Cow<'a, str> {
2104 fn from_iter<I: IntoIterator<Item = char>>(it: I) -> Cow<'a, str> {
2105 Cow::Owned(FromIterator::from_iter(it))
2109 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2110 impl<'a, 'b> FromIterator<&'b str> for Cow<'a, str> {
2111 fn from_iter<I: IntoIterator<Item = &'b str>>(it: I) -> Cow<'a, str> {
2112 Cow::Owned(FromIterator::from_iter(it))
2116 #[stable(feature = "cow_str_from_iter", since = "1.12.0")]
2117 impl<'a> FromIterator<String> for Cow<'a, str> {
2118 fn from_iter<I: IntoIterator<Item = String>>(it: I) -> Cow<'a, str> {
2119 Cow::Owned(FromIterator::from_iter(it))
2123 #[stable(feature = "from_string_for_vec_u8", since = "1.14.0")]
2124 impl From<String> for Vec<u8> {
2125 fn from(string: String) -> Vec<u8> {
2130 #[stable(feature = "rust1", since = "1.0.0")]
2131 impl fmt::Write for String {
2133 fn write_str(&mut self, s: &str) -> fmt::Result {
2139 fn write_char(&mut self, c: char) -> fmt::Result {
2145 /// A draining iterator for `String`.
2147 /// This struct is created by the [`drain`] method on [`String`]. See its
2148 /// documentation for more.
2150 /// [`drain`]: struct.String.html#method.drain
2151 /// [`String`]: struct.String.html
2152 #[stable(feature = "drain", since = "1.6.0")]
2153 pub struct Drain<'a> {
2154 /// Will be used as &'a mut String in the destructor
2155 string: *mut String,
2156 /// Start of part to remove
2158 /// End of part to remove
2160 /// Current remaining range to remove
2164 #[stable(feature = "collection_debug", since = "1.17.0")]
2165 impl<'a> fmt::Debug for Drain<'a> {
2166 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2167 f.pad("Drain { .. }")
2171 #[stable(feature = "drain", since = "1.6.0")]
2172 unsafe impl<'a> Sync for Drain<'a> {}
2173 #[stable(feature = "drain", since = "1.6.0")]
2174 unsafe impl<'a> Send for Drain<'a> {}
2176 #[stable(feature = "drain", since = "1.6.0")]
2177 impl<'a> Drop for Drain<'a> {
2178 fn drop(&mut self) {
2180 // Use Vec::drain. "Reaffirm" the bounds checks to avoid
2181 // panic code being inserted again.
2182 let self_vec = (*self.string).as_mut_vec();
2183 if self.start <= self.end && self.end <= self_vec.len() {
2184 self_vec.drain(self.start..self.end);
2190 #[stable(feature = "drain", since = "1.6.0")]
2191 impl<'a> Iterator for Drain<'a> {
2195 fn next(&mut self) -> Option<char> {
2199 fn size_hint(&self) -> (usize, Option<usize>) {
2200 self.iter.size_hint()
2204 #[stable(feature = "drain", since = "1.6.0")]
2205 impl<'a> DoubleEndedIterator for Drain<'a> {
2207 fn next_back(&mut self) -> Option<char> {
2208 self.iter.next_back()
2212 #[unstable(feature = "fused", issue = "35602")]
2213 impl<'a> FusedIterator for Drain<'a> {}
2215 /// A splicing iterator for `String`.
2217 /// This struct is created by the [`splice()`] method on [`String`]. See its
2218 /// documentation for more.
2220 /// [`splice()`]: struct.String.html#method.splice
2221 /// [`String`]: struct.String.html
2223 #[unstable(feature = "splice", reason = "recently added", issue = "32310")]
2224 pub struct Splice<'a, 'b> {
2225 /// Will be used as &'a mut String in the destructor
2226 string: *mut String,
2227 /// Start of part to remove
2229 /// End of part to remove
2231 /// Current remaining range to remove
2233 replace_with: &'b str,
2236 #[unstable(feature = "splice", reason = "recently added", issue = "32310")]
2237 unsafe impl<'a, 'b> Sync for Splice<'a, 'b> {}
2238 #[unstable(feature = "splice", reason = "recently added", issue = "32310")]
2239 unsafe impl<'a, 'b> Send for Splice<'a, 'b> {}
2241 #[unstable(feature = "splice", reason = "recently added", issue = "32310")]
2242 impl<'a, 'b> Drop for Splice<'a, 'b> {
2243 fn drop(&mut self) {
2245 let vec = (*self.string).as_mut_vec();
2246 vec.splice(self.start..self.end, self.replace_with.bytes());
2251 #[unstable(feature = "splice", reason = "recently added", issue = "32310")]
2252 impl<'a, 'b> Iterator for Splice<'a, 'b> {
2256 fn next(&mut self) -> Option<char> {
2260 fn size_hint(&self) -> (usize, Option<usize>) {
2261 self.iter.size_hint()
2265 #[unstable(feature = "splice", reason = "recently added", issue = "32310")]
2266 impl<'a, 'b> DoubleEndedIterator for Splice<'a, 'b> {
2268 fn next_back(&mut self) -> Option<char> {
2269 self.iter.next_back()